bloody
bloody

Reputation: 1168

how to switch focus to different application C++ / WinAPI

I want to set focus to a particular user-application (using process name) but from the code running "in background" not from the active process. I need to catch a global event and react by bringing the specific application to the front.

Preconditions:

Actions:

Expected:

Neither SetForegroundWindow() nor SwitchToThisWindow() works because my app is not the active one to trigger switch. It must trigger it "from the background" at any time. Does anybody have the solution? The sample of exemplary code would be very appreciated.

[EDITED]: I found a kind of solution - I use AttachThreadInput() function and put as parameters GetWindowThreadProcessId() of window to be active as first and GetCurrentThreadID() as second parameter. OF course TRUE as third. Than both SetActiveWindow() and SetForegroundWindow() work but... unfortunatelly only while debuging in Visual Studio (2013). When I run .exe file both in Debug and Release version, focus does not fire. Does anyone have an idea why it is so?

Upvotes: 1

Views: 5618

Answers (1)

bloody
bloody

Reputation: 1168

OK, I have found a workaround on the net. I send Alt key as input to the system. Then I can use SetForegroundWindow() successufully. After that the Alt key should be released of course.

//set up a generic keyboard event
INPUT keyInput;
keyInput.type = INPUT_KEYBOARD;
keyInput.ki.wScan = 0; //hardware scan code for key
keyInput.ki.time = 0;
keyInput.ki.dwExtraInfo = 0;

//set focus to the hWnd (sending Alt allows to bypass limitation)
keyInput.ki.wVk = VK_MENU;
keyInput.ki.dwFlags = 0;   //0 for key press
SendInput(1, &keyInput, sizeof(INPUT));
           
SetForegroundWindow(hWnd); //sets the focus 

keyInput.ki.wVk = VK_MENU;
keyInput.ki.dwFlags = KEYEVENTF_KEYUP;  //for key release
SendInput(1, &keyInput, sizeof(INPUT));

Upvotes: 3

Related Questions