Solved

show process window

Posted on 2010-09-20
9
450 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 500 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

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

726 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