将焦点更改为另一个程序 Windows API

Changing focus to another program Windows API

本文关键字:程序 Windows API 另一个 焦点      更新时间:2023-10-16

我正在尝试让我的应用程序将焦点更改为鼠标悬停时发生的任何其他窗口。我正在尝试实现一些拖放功能,但似乎缺少的只是鼠标将我的应用程序移动到另一个应用程序时焦点的变化。

这是我当前的测试功能(我现在在主回调程序中WM_MOUSEMOVE进行,以致笑)

case WM_MOUSEMOVE:
{
    POINT pt;
    GetCursorPos(&pt);
    HWND newHwnd = WindowFromPoint(pt);
    if (newHwnd != g_hSelectedWindow)
    {
        cout << "changing windows" << endl;
        cout << SetWindowPos(newHwnd, HWND_TOP, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE) << endl;
        g_hSelectedWindow = newHwnd;
    }
    CallWindowProc(listproc, hwnd,message,wParam,lParam);
    break;
}

我尝试使用AllowSetForegroundWindow,但它有助于它在给定的范围内找不到它,但是我已经包含了.

任何帮助或建议将不胜感激。

AllowSetForegroundWindow无济于事,除非另一个窗口试图通过调用SetForegroundWindow成为前景窗口。

我很好奇,如果你需要把另一个窗口带到前台,为什么不直接打电话给SetForegroundWindow呢?

更新:所以这是你需要的代码,让它正常工作:

HWND ResolveWindow(HWND hWnd)
{ /* Given a particular HWND, if it's a child, return the parent. Otherwise, if
   * the window has an owner, return the owner. Otherwise, just return the window
   */
    HWND hWndRet = NULL;
    if(::GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD)
        hWndRet = ::GetParent(hWnd);
    if(hWndRet == NULL)
        hWndRet = ::GetWindow(hWnd, GW_OWNER);
    if(hWndRet != NULL)
        return ResolveWindow(hWndRet);
    return hWnd;    
}
HWND GetTopLevelWindowFromPoint(POINT ptPoint)
{ /* Return the top-level window associated with the window under the mouse 
   * pointer (or NULL) 
   */
    HWND hWnd = WindowFromPoint(ptPoint);
    if(hWnd == NULL)
        return hWnd;    
    return ResolveWindow(hWnd);
}

只需从WM_MOUSEMOVE处理程序调用GetTopLevelWindowFromPoint(pt),如果您返回有效的 HWND,那么它将是一个顶级窗口,可以使用 SetForegroundWindow 将其置于前台。

我希望这有所帮助。