Hi, I try to build a console app to run an exe in a new Windows desktop. This is my code:
var
deskHnd : HDESK;
curDesk : HDESK;
pstart : STARTUPINFO;
pinfo : PROCESS_INFORMATION;
newDesk : string;
begin
try
if ParamCount<1 then
begin
writeln('Usage: deskrun [exe file]');
Exit;
end;
if not(FileExists(ParamStr(1))) or (LowerCase(ExtractFileExt(ParamStr(1)))<>'.exe') then
begin
writeln('Executable not found!');
Exit;
end;
curDesk := GetThreadDesktop(0);
Randomize;
newDesk := 'Run-In-New-Desktop-'+IntToStr(Random(MaxInt));
deskHnd := CreateDesktop(PChar(newDesk),nil,nil,0,GENERIC_ALL,nil);
ZeroMemory(@pstart, SizeOf(pstart));
pstart.cb := SizeOf(pstart);
pstart.lpDesktop := PChar(newDesk);
CreateProcess(PChar(ParamStr(1)),nil,nil,nil,false,0,nil,nil,pstart,pinfo);
CloseHandle(pinfo.hThread);
SwitchDesktop(deskHnd);
WaitForSingleObject(pinfo.hProcess, INFINITE);
CloseDesktop(deskHnd);
SwitchDesktop(curDesk);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
The code run ok, it's just an issue which bothers me. Everytime I close the exe run by this program, the desktop does not switch back to original desktop (SwitchDesktop(curDesk)) does not work, even the CloseDesktop(deskHnd) seems like does not working as well. I need to press Ctrl+Alt+Del and click on Cancel for me to return to original desktop. Any idea how to fix this?