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);

原文地址:https://www.cnblogs.com/xuhuajie/p/14782205.html