?
Solved

show process window

Posted on 2010-09-20
9
Medium Priority
?
451 Views
Last Modified: 2012-05-10
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
Comment
Question by:darrgyas
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 33717880
>>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
 

Author Comment

by:darrgyas
ID: 33717956
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
 
LVL 86

Expert Comment

by:jkr
ID: 33717999
What Windows version are you on?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:darrgyas
ID: 33718008
server 2003
0
 

Author Comment

by:darrgyas
ID: 33718019
I tried CREATE_NEW_CONSOLE - no effect
0
 
LVL 86

Accepted Solution

by:
jkr earned 2000 total points
ID: 33718045
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
 

Author Comment

by:darrgyas
ID: 33718281
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
 
LVL 86

Expert Comment

by:jkr
ID: 33718579
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
 

Author Comment

by:darrgyas
ID: 33718607
Thank you, I appreciate it.
0

Featured Post

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question