简体   繁体   中英

How to detect mouse cursor is outside a windows?

I've written a code that dynamically creates a POPUP style window when the user clicks inside my main app window. Now I'd like the POPUP window to be automatically destroyed when the mouse cursor goes out of the POPUP wnd region. I know that i have probably handle the WM_MOUSEMOVE message but how to do that? Please provide a simple code for that if You can...

Use the WM_MOUSELEAVE message instead. However, note that this message has to be explicitly requested via TrackMouseEvent() , which your window can call when it receives its first WM_MOUSEMOVE message.

As @Remy Lebeau said, the following is the code implementation.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static BOOL Tracing = FALSE;
    switch (message)
    {
    case WM_MOUSELEAVE:
    {
        DestroyWindow(hWnd);
        break;
    }
    case WM_MOUSEMOVE:
    {
        if (!Tracing)
        {
            Tracing = TRUE;

            TRACKMOUSEEVENT tme{};
            tme.cbSize = sizeof(TRACKMOUSEEVENT);
            tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hWnd;

            TrackMouseEvent(&tme);
        }
        break;
    }
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

you can compare the event.target and event.currentTarget, if both are same then you are out side of popup window else in side the popup window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM