Search code examples
winapichildwindow

display rectangle on a win32 child window if cursor is on it and erase if cursor leaves child window


I need to display some shapes (5 rectangles to be precise) on my caption less child window when ever my cursor is on the window, and erase them when cursor leaves the window; i.e enters into the parent window region.

I am tracking the mouse movement to the child window through NCHITTEST, and the rectangles pop up perfectly. But i cant get them to disappear when my cursor leaves the child window, they just remain there on the client area until WM_PAINT is called on to the window.

Can anybody tell me how to achieve this functionality? I need to use the NCHITTEST case as rest of my functionality depends on it. I have tried tracking mouse_move and lbuttondown events, but these events aren't being captured along with nchittest.


Solution

  • Look at the TrackMouseEvent() function.

    This needs to be called when the mouse enters the window (WM_MOUSEMOVE if it's not already being tracked) and will notify your window when the mouse leaves (WM_MOUSELEAVE).

    Here's some sample VB6 code but the should be easily convertable to any other language.

    Select Case Msg
        Case WM_MOUSEMOVE
          If Not MouseInWindow Then
            Dim ET As TRACKMOUSEEVENTTYPE
            'Set up the mouse leave notification
            ET.cbSize = Len(ET)
            ET.hwndTrack = Me.hWnd
            ET.dwFlags = TME_HOVER Or TME_LEAVE
            ET.dwHoverTime = 0
            TrackMouseEvent ET
    
            MouseInWindow = True
            'The mouse has just entered
            Redraw
          End If
    
        Case WM_MOUSELEAVE
          If MouseInWindow Then
            MouseInWindow = False
            'The mouse has just left
            Redraw
          End If
    End Select