I’m writing a program that would focus on the process window and bring it to the foreground given the process PID. I’ve came up with the following program in C, but it doesn’t always work despite the checks to ensure that the window is focused.
I’ve read other posts but didn’t find a solution to my problem.
#include <windows.h>
#include <stdio.h>
BOOL CALLBACK
EnumWindowsProc(HWND hwnd, LPARAM lParam) {
DWORD dwPID;
GetWindowThreadProcessId(hwnd, &dwPID);
if (dwPID == (DWORD)lParam) {
if (!IsWindowVisible(hwnd)) {
ShowWindow(hwnd, SW_RESTORE);
}
if (!SetForegroundWindow(hwnd)) {
printf("can't set window to foreground.n");
}
return FALSE;
}
return TRUE;
}
int
main(int argc, char *argv[]) {
if (argc != 2) {
printf("Run as: %s <PID>n", argv[0]);
return 1;
}
DWORD pid = (DWORD)atoi(argv[1]);
EnumWindows(EnumWindowsProc, (LPARAM)pid);
return 0;
}
Here is the entire program.
IsWindowVisible
checks whether the window is visible and SetForegroundWindow()
ensures that the window is focused.
The strange thing is, this program works on some windows, but at other times, the window is “focused”, but the window isn’t brought to the foreground (or visible on the monitor).
From another post, I read that from MSDN:
The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:
The process is the foreground process.
The process was started by the foreground process.
The process received the last input event.
There is no foreground process.
The process is being debugged.
The foreground process is not a Modern Application or the Start Screen.
The foreground is not locked (see LockSetForegroundWindow).
The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
No menus are active.
To be fairly honest, I have no clue whether that process window violates any of these conditions. I would think that SetForegroundWindow
would fail if the window did violate any of these (which would be caught by the if check) but it didn’t.
Any idea how I go about fixing this such that it both focus on the window and bring it to foreground?