How to detect when the user locks/unlocks the screen in Windows 7?
I found this question which has an answer for C#, but I'd like to use it in Delphi 2009. I'd guess there is some windows message (like these) which could do the work. This is the code I tried, but it didn't work:
const
NOTIFY_FOR_ALL_SESSIONS = 1;
{$EXTERNALSYM NOTIFY_FOR_ALL_SESSIONS}
NOTIFY_FOR_THIS_SESSION = 0;
{$EXTERNALSYM NOTIFY_FOR_THIS_SESSION}
type
TfrmAlisson = class(TForm)
lbl2: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
public
FLockedCount: Integer;
procedure WndProc(var Message: TMessage); override;
function WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool; stdcall;
function WTSUnRegisterSessionNotification(hWND: HWND): bool; stdcall;
end;
implementation
uses
// my impl uses here
procedure TfrmAlisson.FormCreate(Sender: TObject);
begin
if (WTSRegisterSessionNotification(Handle, NOTIFY_FOR_THIS_SESSION)) then
ShowMessage('Nice')
else
begin
lastError := GetLastError;
ShowMessage(SysErrorMessage(lastError));
end;
end;
procedure TfrmAlisson.FormDestroy(Sender: TObject);
begin
WTSUnRegisterSessionNotification(Handle);
end;
procedure TfrmAlisson.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_WTSSESSION_CHANGE:
begin
if Message.wParam = WTS_SESSION_LOCK then
begin
Inc(FLockedCount);
end;
if Message.wParam = WTS_SESSION_UNLOCK then
begin
lbl2.Caption := 'Session was locked ' +
IntToStr(FLockedCount) + ' times.';
end;
end;
end;
inherited;
end;
function TfrmAlisson.WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool;
external 'wtsapi32.dll' Name 'WTSRegisterSessionNotification';
function TfrmAlisson.WTSUnRegisterSessionNotification(hWND: HWND): bool;
external 'wtsapi32.dll' Name 'WTSUnRegisterSessionNotification';
When FormCreate
executes, WTSRegisterSessionNotification
returns false
and the last OS error returns Invalid Parameter.
wParam
isWTS_SESSION_LOCK
orWTS_SESSION_UNLOCK
your case – PlacardWTSRegisterSessionNotification
, it returns false and if I get last OS error, it returns invalid parameter (in portuguese, in my case). – SqualorCreateWnd()
method. – Mystical