views:

165

answers:

2

I'm creating an application with its main window hidden by using the following code:

STARTUPINFO siStartupInfo;
PROCESS_INFORMATION piProcessInfo;

memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));

siStartupInfo.cb = sizeof(siStartupInfo);
siStartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES;
siStartupInfo.wShowWindow = SW_HIDE;

if(CreateProcess(MyApplication, "", 0, 0, FALSE, 0, 0, 0, &siStartupInfo, &piProcessInfo) == FALSE)  
{
 // blah    
 return 0;
}

Everything works correctly except my main application (the one calling this code) window loses focus when I open the new program. I tried lowering the priority of the new process but the focus problem is still there.

Is there anyway to avoid this? furthermore, is there any way to create another process without using CreateProcess (or any of the API's that call CreateProcess like ShellExecute)?

My guess is that my app is losing focus because it was given to the new process, even when it's hidden.

To those of you curious out there that will certainly ask the usual "why do you want to do this", my answer is because I have a watchdog process that cannot be a service and it gets started whenever I open my main application. Satisfied?

Thanks for the help. Code will be appreciated. Jess.

A: 

Clearly the target application is not honoring the ShowWindow flags. You need to fix the launched application so that its not being greedy.

Chris Becke
thank you. The launched app runs with the lowest priority possible. what else can you do?
Jessica
Its got nothing to do with priority. Windows will not ever take activation (and thus focus) from a window unless another window attempts to take activation. Which means that, all your SW_HIDE hints to the contrary - the application is attempting to activate a top level window. Add a WM_ACTIVATE handler to your main window and breakpoint it and windows will tell you the hwnd of the thieving window.
Chris Becke
OK. I have to idea how to capture that specific message but I'll try to find out. Do you know a way to do it?
Jessica
The launching application has a window that is loosing focus/activation yes? This window will have a WindowProc / some kind of message handler if you are using a framework like MFC. You need to find the windowproc, or message map, and add a handler for WM_ACTIVATE or OnActivate.
Chris Becke
A: 

The application you are running is taking the Window focus.

One way to work around this problem is to start your new process in a new desktop. This would prevent the application from stealing the window focus on your desktop.

The code to run a process on a new desktop should look something like this:

HDESK hOld = GetThreadDesktop( GetCurrentThreadId() );
HDESK hNew = OpenDesktop( "name", 0, FALSE, GENERIC_ALL );
SetThreadDesktop( hNew );
CreateProcess( ... );
SetThreadDesktop( hOld );
CloseDesktop( hNew );
Jason