在多进程开发中,经常会遇到主进程将副进程窗体置前或者副进程将主进程窗体置前的问题,但是简单的调用::SetForegroundWindow(hwnd_);
经常会遇到不生效的问题,对此微软官方解释是:
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.
为了解决此问题,可采用如下方法:
DWORD windowThreadProcessId = GetWindowThreadProcessId(GetForegroundWindow(), LPDWORD(0));
DWORD currentThreadId = GetCurrentThreadId();
if (windowThreadProcessId != currentThreadId)
{
::AttachThreadInput(windowThreadProcessId, currentThreadId, true);
::BringWindowToTop(hwnd_);
::AttachThreadInput(windowThreadProcessId, currentThreadId, false);
}
else
{
::SetForegroundWindow(hwnd_);
}
及先判断当前进程是否是活动窗体,如果不是将本进程加入到活动进程中,然后再调用置前方法