• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

show process window

Hi all,

I have written a service that starts a process:

                STARTUPINFO                  si;
            PROCESS_INFORMATION pi;

            memset(&pi, 0, sizeof(pi));
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            si.dwFlags = STARTF_USESHOWWINDOW;
            si.wShowWindow = SW_NORMAL | SW_SHOW;

            CreateProcess(<ExeName>, NULL, NULL, NULL, FALSE,
                  CREATE_DEFAULT_ERROR_MODE, NULL,<WorkingFolder>, &si, &pi))

This works, but the window for <ExeName> is not shown (it's a console application)

How do I create that process so that console window will always be shown?

Thank you.
0
darrgyas
Asked:
darrgyas
  • 5
  • 4
1 Solution
 
jkrCommented:
>>I have written a service that starts a process
>>[...]
>>This works, but the window for <ExeName> is not shown (it's a console
>>application)

The reason for this is that services run on their own desktop, which is invisible to the logged on user. If you want the window to be visible, you need to either set your service to interact with the user's desktop using 'SERVICE_INTERACTIVE_PROCESS' when calling 'CreateService()' (http://msdn.microsoft.com/en-us/library/ms682450(VS.85).aspx) - which is not recommended for systems more recent than XP - or go the hard way as outlined in http://support.microsoft.com/kb/327618 ("Security, services and the interactive desktop in Windows"). See also the sample code in http://support.microsoft.com/kb/165194 ("CreateProcessAsUser() windowstations and desktops") as well as http://www.microsoft.com/whdc/system/sysinternals/Session0Changes.mspx ("Impact of Session 0 Isolation on Services and Drivers in Windows").
In a nutshell: This is helluva a task if you do not want to risk a security breach and use deprecated methods like SERVICE_INTERACTIVE_PROCESS.

0
 
darrgyasAuthor Commented:
If I start some dialog-based applicationfrom the service, like notepad - it is visible.
Also, if checking "allow this service to interact..." in the services applet does not do anything, will doing it programmatically work?
0
 
jkrCommented:
What Windows version are you on?
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
darrgyasAuthor Commented:
server 2003
0
 
darrgyasAuthor Commented:
I tried CREATE_NEW_CONSOLE - no effect
0
 
jkrCommented:
Server 2003 should support 'SERVICE_INTERACTIVE_PROCESS' as well as setting that in the control panel. BTW, you could also use the following technique to launch an application in the security context of the logged on user:
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <malloc.h>
#include <lmcons.h>

#pragma comment(lib,"kernel32.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"advapi32.lib")

void
__cdecl
DbgReport ( char* __pszFormat, ...) {

    static char s_acBuf [ 2048];

    va_list _args;

    va_start ( _args, __pszFormat);

    vsprintf ( s_acBuf, __pszFormat, _args);

    OutputDebugStringA ( s_acBuf);

    va_end ( _args);
}

DWORD ExecuteCmd   (   LPSTR   pszCmd, BOOL bShow, HANDLE hToken)
{
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    BOOL                bRes;

    DWORD               dwCode  =   0;

    MSG                msg;

    ZeroMemory  (   &si,    sizeof  (   STARTUPINFO));

    si.cb           =   sizeof  (   STARTUPINFO);
    si.dwFlags      =   STARTF_USESHOWWINDOW;
    si.wShowWindow  =   bShow ? SW_SHOWNORMAL : SW_HIDE;

    bRes    =   CreateProcessAsUser   (  hToken,
                                   NULL,
                                   pszCmd,
                                   NULL,
                                   NULL,
                                   TRUE,
                                   NORMAL_PRIORITY_CLASS,
                                   NULL,
                                   NULL,
                                   &si,
                                   &pi
                               );

    
    CloseHandle (   pi.hProcess);
    CloseHandle (   pi.hThread);

    return  (   0);
}


DWORD GetExplorerProcessID()
{
      HANDLE hSnapshot;
      PROCESSENTRY32 pe32;
      ZeroMemory(&pe32,sizeof(pe32));
      DWORD temp;

    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);
      
      pe32.dwSize = sizeof(PROCESSENTRY32);

      if(Process32First(hSnapshot,&pe32))
      {
            do
            {
                  if(!strcmp(pe32.szExeFile,"explorer.exe"))
                  {
                        temp = pe32.th32ProcessID;
                        break;
                  }

            }while(Process32Next(hSnapshot,&pe32));
      }

    DbgReport("Explorer PID: %d\n", temp);

return temp;
}

BOOL EnableDebugPriv  (   BOOL    bEnable)
{
   HANDLE           hToken;
   TOKEN_PRIVILEGES tp;

   if   (   !OpenProcessToken   (   GetCurrentProcess   (),
                                    TOKEN_ADJUST_PRIVILEGES,
                                    &hToken
                                )
        )   return  (   FALSE);


   tp.PrivilegeCount    =   1;

   LookupPrivilegeValue (   NULL,
                            SE_DEBUG_NAME,
                            &tp.Privileges  [   0].Luid
                        );

   tp.Privileges    [   0].Attributes   =       bEnable
                                            ?   SE_PRIVILEGE_ENABLED
                                            :   0;

   AdjustTokenPrivileges    (   hToken,
                                FALSE,
                                &tp,
                                sizeof  (   tp),
                                NULL,
                                NULL
                            );

   return   (   GetLastError()  ==   ERROR_SUCCESS);
}

void GetSidUser(PSID psid,char*pName, DWORD dwNameSize) {

    char                    acReferencedDomain  [   LM20_DNLEN  +   1];
    DWORD                   dwDomainBufSize     =   sizeof  (   acReferencedDomain);
    SID_NAME_USE            eUse;

               //  lookup clear text name of the owner
                if  (   !LookupAccountSid   (   NULL,
                                                psid,
                                                pName,
                                                &dwNameSize,
                                                acReferencedDomain,
                                                &dwDomainBufSize,
                                                &eUse
                                            )
                    )
                    {
                        DWORD dwErr   =   GetLastError    ();

                        DbgReport("LookupAccountSid() failed: %d\n", dwErr);

                    } else DbgReport("SID represents %s\\%s\n", acReferencedDomain, pName);
}

void ImpersonateInteractiveUser(LPSTR pCmd, BOOL bShow)
{
   HANDLE hToken = NULL;                
   HANDLE hProcess = NULL;
   char                    acName  [   LM20_DNLEN  +   1];
   DWORD                   dwNameSize     =   sizeof  (   acName);

   DWORD processID = GetExplorerProcessID();
   if( processID)
    {
    hProcess =
         OpenProcess(  
               PROCESS_ALL_ACCESS,
         TRUE,
          processID );

    if( hProcess)
        {
        if( OpenProcessToken(
                    hProcess,
             TOKEN_ALL_ACCESS,
             &hToken))
        {
         TOKEN_USER* ptu;
         DWORD dw;
         GetTokenInformation(hToken,TokenUser,NULL,0,&dw);
         ptu = (TOKEN_USER*) _alloca(dw);

         if (!GetTokenInformation(hToken,TokenUser,ptu,dw,&dw)) DbgReport("GetTokenInformation() failed, reason: %d\n", GetLastError());
         GetSidUser(ptu->User.Sid,acName,dwNameSize);

         if (!ImpersonateLoggedOnUser( hToken)) DbgReport("ImpersonateLoggedOnUser() failed, reason: %d\n", GetLastError());

         DbgReport("Launching command: %s as \'%s\'\n", pCmd, acName);
         ExecuteCmd(pCmd,bShow,hToken);

          CloseHandle( hToken );
        } else DbgReport("OpenProcessToken() failed, reason: %d\n", GetLastError());
        CloseHandle( hProcess );
    } else DbgReport("OpenProcess() failed, reason: %d\n", GetLastError());
   } 
}


int main (int argc, char** argv) {

  if (2 > argc) return -1;

  EnableDebugPriv(TRUE);

  BOOL bShow = TRUE;

  if (argc == 3) bShow = strcmp(argv[2],"/HIDE");

  if (!bShow) DbgReport("... using /HIDE\n");

  ImpersonateInteractiveUser(argv[1], bShow);

  return 0;

}

Open in new window

0
 
darrgyasAuthor Commented:
That works, thank you.
The points well deserved, but just to push my luck is it possible to show console for the service itself?
0
 
jkrCommented:
I am afraid that this would require opening the window station, adjusting the privileges etc. - IOW a lot of effort. I'd rather recommend to use an application that is launech in the user's context and with which you communicate with some IPC means if you need to display any status updates or something similar.
0
 
darrgyasAuthor Commented:
Thank you, I appreciate it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now