开发者

How to know when mouse leaves my window when WM_MOUSELEAVE sometimes doesn't work?

I'm having a problem with TrackMouseEvent and WM_MOUSELEAVE. I call TrackMouseEvent in my app when the mouse is over my window in the WM_SETCURSOR and WM_NCHITTEST handlers. The problem is that if I move the mouse very quickly out of my w开发者_如何学编程indow, I don't get WM_MOUSELEAVE at all.

I'm fairly sure I'm using this correctly, because normal, slower movements will produce WM_MOUSELEAVE. It's only when the mouse is moving too fast that it doesn't get generated. The problem is, how am I supposed to detect this? My app isn't always in the foreground, so I'm not sure SetCapture will do what I need.


It could be that WM_NCMOUSELEAVE is what you need.

Edit: It's worth mentioning in my opinion that the docs imply that you must call TrackMouseEvent. However, I never did this and I still got the MOUSELEAVE message. Perhaps this call is now redundant and/or buggy?


My experience has been that TrackMouseEvent is not reliable. When I've needed reliable mouse leaves, I've used timers instead. (apologies for cutting this from an MFC project)

void OnNotifyMouseLeave()
{
    // Mouse is gone
}

void OnMouseMove(UINT nFlags, CPoint point) 
{
    if ( m_uTimerId == 0 )
        m_uTimerId = SetTimer( MOUSELEAVE, 250, NULL );

    ...
}

void OnTimer( UINT_PTR nIDEvent ) 
{
    if ( nIDEvent == MOUSELEAVE )
    {
        POINT pt;
        RECT rect;
        GetCursorPos( &pt );
        GetWindowRect( &rect );
        if ( !PtInRect( &rect, pt ) )
        {   OnNotifyMouseLeave();
            if ( m_uTimerId != 0 )
            {   KillTimer( m_uTimerId );
                m_uTimerId = 0;
            }
        }
    }

    ...
}


MouseLeave is finicky. SetCapture is what you need to use. Besides I don't think you can get mouse messages reliably if your app isn't in focus.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜