uses JwaWinbase, JwaWtsApi32; var hToken: THandle; si: _STARTUPINFOA; pi: _PROCESS_INFORMATION;
var Ret: Cardinal; sTitle: string; sMsg: string; begin ZeroMemory(@si, SizeOf(si)); si.cb := SizeOf(si); si.lpDesktop := nil; if WTSQueryUserToken(WtsGetActiveConsoleSessionID, hToken) then begin if CreateProcessAsUser(hToken, nil, 'notepad.exe', nil, nil, False, 0, nil, nil, si, pi) then begin // Do some stuff end; end; end;
I specified WtsGetActiveConsoleSessionID as the SessionID, this function retrieves the Terminal Services session currently attached to the physical console. The physical console is the monitor, keyboard, and mouse. Note that it is not necessary that Terminal Services be running for this function to succeed. In Windows 2000 the console is always session 0 but for Windows XP/2003/Vista this can be any number. So if you want to launch a process in session 5 the code is:
if WTSQueryUserToken(5, hToken) then begin if CreateProcessAsUser(hToken, nil, 'notepad.exe', nil, nil, False, 0, nil, nil, si, pi) then begin // Do some stuff end; end;
WtsQueryUserToken is defined in the unit JwaWtsApi32 and WtsGetActiveConsoleSessionID is defined in the unit JwaWinBase. Both units are part of theJedi APILibrary.
This will launch notepad in the console session but offcourse you can replace the function WtsGetActiveConsoleSessionId with a specific SessionID. Just remember that only the system account is allowed to use WtsQueryUserToken. So you will need to launch this code from a service.