在服务程序中创建用户进程的方法

 
1.   创建service时一定要加上 
SERVICE_INTERACTIVE_PROCESS
属性,既允许该服务与桌面进行交互, 否则创建的用户界面不能显示,
例如:
 SC_HANDLE hService = ::CreateService(
        hSCM, m_szServiceName, m_szServiceName,
        SERVICE_ALL_ACCESS, 、
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
        SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
        szFilePath, NULL, NULL, _T("RPCSS\0"), NULL, NULL);

 2.  创建用户进程方法:

方法1:
   HWND deskton;
    DWORD desktonID;
    HANDLE hProc;
     
    deskton 
=  FindWindow( " Progman " " Program Manager " ); //有时候Findwindow这个函数执行不成功, 可以用 GetDesktopWindow(),代替
    GetWindowThreadProcessId(deskton,
& desktonID);
    hProc 
=  OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,desktonID);
    
if  ( hProc  ==  NULL )
    
{
        
return 0;
    }

    
if  (  ! OpenProcessToken(hProc,TOKEN_DUPLICATE, & hToken) )
    
{
        
return 0;
    }

    
if  ( DuplicateTokenEx(hToken,TOKEN_ALL_ACCESS,NULL,SecurityImpersonation,TokenPrimary, & hTokenNew ))
    
{
        memset(
&startinfo, 0sizeof(STARTUPINFO));
        startinfo.cb 
= sizeof(STARTUPINFO);
        startinfo.dwFlags 
= STARTF_USESHOWWINDOW;
        startinfo.wShowWindow 
= SW_SHOWNORMAL;
    }
 
    CreateProcessAsUser( hTokenNew,
                                        
" C:/WINDOWS/system32/notepad.exe " ,
                                          NULL,
                                          NULL,
                                          NULL,
                                          FALSE,
                                          CREATE_DEFAULT_ERROR_MODE,   
                          NULL,
                                          NULL,
                                         
& startinfo, & procinfo);
方法2:

HWINSTA hWinSta;
HDESK   hDesk;
hWinSta = ::OpenWindowStation (_T("Winsta0"),false,MAXIMUM_ALLOWED);
if(::SetProcessWindowStation (hWinSta))
{
    TRACE(L"SetProcessWindowStation OK\n");
}
else
{
    TRACE(DBG_VERBOSE,L"SetProcessWindowStation Error\n");
}
 
    
hDesk = ::OpenDesktop (_T("Default"),0,false,MAXIMUM_ALLOWED);
if(::SetThreadDesktop (hDesk))
{
    TRACE(L"SetProcessWindowStation OK\n");
}
else
{
    TRACE(L"SetProcessWindowStation Error\n");
}
::ShellExecuteW(GetDesktopWindow (),NULL,_T("C:/WINDOWS/system32/notepad.exe"),NULL,NULL,SW_SHOW);




你可能感兴趣的:(在服务程序中创建用户进程的方法)