Search code examples
delphidelphi-10-seattle

SetThreadDesktop: ERROR_INVALID_HANDLE


Why every time that code below is executed, SetThreadDesktop() fails with the following message:

ERROR_INVALID_HANDLE

The new desktop is created with success, then mean that have a handle opened.

What's happening?

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows,
  SysUtils;

var
  _hDesk: HDESK;

begin
  try
    _hDesk := OpenDesktop('test', 0, True, GENERIC_ALL);

  if _hDesk = 0 then
    CreateDesktop('test', nil, nil, 0, GENERIC_ALL, nil);

  if not SetThreadDesktop(_hDesk) then
  begin
    Writeln(SysErrorMessage(GetLastError));
  end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

Solution

  • CreateDesktop returns a handle. You need to use that handle to switch your thread to the desktop.

    _hDesk := CreateDesktop('test', nil, nil, 0, GENERIC_ALL, nil);
    

    Also be sure to check if the function succeeds, see documentation for how.