SetForegroundWindow的失效问题: 跨进程的窗口前置。

Posted 烟波--钓徒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SetForegroundWindow的失效问题: 跨进程的窗口前置。相关的知识,希望对你有一定的参考价值。

          

SetForegroundWindow function

 

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.

An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.

A process that can set the foreground window can enable another process to set the foreground window by calling the AllowSetForegroundWindow function. The process specified by dwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process calls AllowSetForegroundWindow, unless that process is specified.

The foreground process can disable calls to SetForegroundWindow by calling the LockSetForegroundWindow function.

 

 

想要SetForegroundWindow生效,必须得是前置的进程(活动的进程)。可以用以下方法实现。

//跨进程SetForegroundWindow 会失效,需要如下代码搞一搞。
HWND hForeWnd = ::GetForegroundWindow();
DWORD dwCurID = ::GetCurrentThreadId();
DWORD dwForeID = ::GetWindowThreadProcessId(hForeWnd, NULL);
::AttachThreadInput(dwCurID, dwForeID, TRUE);
::ShowWindow(m_hWnd, SW_SHOWNORMAL);
::SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
::SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
::SetForegroundWindow(m_hWnd);
::BringWindowToTop(m_hWnd);
::AttachThreadInput(dwCurID, dwForeID, FALSE);

 

以上是关于SetForegroundWindow的失效问题: 跨进程的窗口前置。的主要内容,如果未能解决你的问题,请参考以下文章

SetForegroundWindow 在对话框窗口中使用时不起作用

SetForegroundWindow 没有激活我的窗口

SetForegroundWindow 不适用于最小化进程[重复]

使用 JNA SetForeGroundWindow

setForegroundWindow 的使用方法有哪些?

win32设置当前窗口——SetForegroundWindow,SetActiveWindow, or ShowWindow?