지정한 터미널 세션에서 프로그램을 시작하는 방법

First we obtain the user’s primary access token with the WtsQueryUserToken  API call. To call this function successfully, the calling application must be running within the context of the LocalSystem account and have the SE_TCB_NAME privilege (LocalSystem has this privilege by default). Since the function returns a primary acces token we can just pass this to CreateProcessAsUser and voila!
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.

좋은 웹페이지 즐겨찾기