how to make CreateProcess open new process in focus and not in background [duplicate]
Asked Answered
A

1

1

I created a very simple Win program. it opens notepad and after 5 seconds it opens calc. the problem is that always the first program opens in background and not in focus (see the picture). the second program opens in focus. i've been wondering about this for a while and i can't figure out why it happens or how to open the first program in focus.

I am using visual studio 2013 with the default Windows Application settings.

EDIT: this is NOT a duplicate question, what I am asking here is WHY the same CreateProcess() function creates one time the process in background and one time in focus!

notepad opens in background

#include <Windows.h>


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    STARTUPINFO si = { 0 };
    PROCESS_INFORMATION pi = { 0 };
    si.cb = sizeof(si);
    CreateProcess(L"c:\\windows\\system32\\notepad.exe", NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

    Sleep(5000);

    STARTUPINFO si2 = { 0 };
    PROCESS_INFORMATION pi2 = { 0 };
    si2.cb = sizeof(si2);
    CreateProcess(L"c:\\windows\\system32\\calc.exe", NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si2, &pi2);

    return 0;
}
Atterbury answered 30/7, 2014 at 10:48 Comment(0)
A
3

found a way to solve this, very strange, and i have no idea why it works, but it works.

if i add:

MSG msg;
TranslateMessage(&msg);

in the WinMain, then the process I create gets in focus, very strange. can someone explain why it works?

Atterbury answered 30/7, 2014 at 11:45 Comment(2)
I created a question on the programmer's stackexchange about this.Organicism
You should initialize msg, otherwise you're passing an uninitialized object to an API function. The trick still works when we have MSG msg = { 0 }; and could be more reliable. If it's uninitialized, you never know: maybe it will work most of the time, but from time to time TranslateMessage function won't like the particular garbage bit pattern in msg and throw a fit before the workaround effect takes place.Organicism

© 2022 - 2024 — McMap. All rights reserved.