The WinSta0_DesktopSwitch Event allows an application to check for a desktop switch. The following examples demonstrates how we can wait for such an Event. To test it, simply lock and unlock the workstation. Both wait function will return on the two desktop switching.

uses
  SysUtils
  JwaWindows;

var H : THandle;
begin
  H := OpenEvent(SYNCHRONIZE, false, ‘WinSta0_DesktopSwitch’);
  if H = 0 then
  begin
    writeln(SysErrorMessage(GetLasterror));
    readln;
  end;

  WaitForSingleObject(H,INFINITE);
  writeln(‘OK1′);

  WaitForSingleObject(H,INFINITE);
  writeln(‘OK2′);

  writeln(‘Switched’);
  readln;
end.

You should know that each session (0…x) has its own event. You can’t use this mechanism directly in a service (especially not in Vista due to session isolation).