I have a service script for Windows in Delphi Tokyo. The service starts at system startup and creates the process x correctly. Start a timer that cyclically checks if the process is started or not and if it is not, it tries to start it but fails with error code 1008.
function TMyservice.CreaProcessoComeUtenteX(const FileName, Params: string;
WindowState: Word): Boolean;
var
SessionID: DWORD;
UserToken: THandle;
CmdLine: PChar;
si: _STARTUPINFOW;
pi: _PROCESS_INFORMATION;
ExitCode: Cardinal;
begin
SessionId:= WtsGetActiveConsoleSessionID;
if SessionID = $FFFFFFFF then
begin
ADDLOG('Exit from CreaProcessoComeUtenteX '+IntToStr(SessionID));
Result := false;
Exit;
end;
if WTSQueryUserToken(SessionID, UserToken) then
begin
CmdLine:= PWideChar(FileName+Params);
ZeroMemory(@si, SizeOf(si));
si.cb := SizeOf(si);
SI.lpDesktop := PChar('winsta0\Default');
SI.dwFlags := STARTF_USESHOWWINDOW;
if WindowState = 1 then
SI.wShowWindow := SW_SHOWNORMAL;
if WindowState = 0 then
SI.wShowWindow := SW_MINIMIZE;
ZeroMemory(@pi, SizeOf(pi));
try
CreateProcessAsUser(UserToken, nil, CmdLine, nil, nil, False,
0, nil, nil, si, pi);
ADDLOG(' Create process Ok');
result := true;
except on E: Exception do
begin
// Log exception ...
result := false;
ADDLOG('Err proc: '+ E.Message);
end;
end;
CloseHandle(UserToken);
end else
begin
// Log GetLastError ...
Result := false;
ADDLOG('QToken: '+IntToStr(GetLastError));
end;
end;
This code impersonate current user
function TInfBabeleDS.ConnectAs(const lpszUsername,
lpszPassword: string): Boolean;
var
hToken : THandle;
begin
Result := LogonUser(PChar(lpszUsername), nil, PChar(lpszPassword), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, hToken);
if Result then
Result := ImpersonateLoggedOnUser(hToken)
else
RaiseLastOSError;
end;