1
votes

I am trying to draw a rectangle around the current cursor's position in MFC. It works when I move the mouse but the rectangle is disappeared when I stop moving the mouse.

void CView1::OnMouseMove(UINT nFlags, CPoint point)
{
    if (!m_mouse_tracking)
    {
        TRACKMOUSEEVENT tme;
        tme.cbSize = sizeof(TRACKMOUSEEVENT);
        tme.dwFlags = TME_HOVER;
        tme.hwndTrack = this->m_hWnd;
        tme.dwHoverTime = HOVER_DEFAULT;

        if (::_TrackMouseEvent(&tme))
        {
            m_mouse_tracking = true;

            // Draw the 1st rect
            draw_rect_(m_pDC);
        }
    }
    else
    {
        // Draw new rect and erase old rect
        RedrawWindow(NULL, NULL, RDW_INVALIDATE);
        draw_rect_(m_pDC);
    }
}

void CView1::OnMouseHover(UINT nFlags, CPoint point)
{
    m_mouse_tracking = false;

    draw_rect_(m_pDC);
}

Is there something wrong with my source code? Please, help me.

1
You call RedrawWindow to invalidate the client area, which will cause a repaint some time after draw_rect_() has returned. That's propably not what you expected. Try RDW_UPDATENOW, but actually you should do all painting in WM_PAINT while anywhere else you only invalidate the client area.zett42
Is m_pDC a memory DC? Is there a memory bitmap? Give more information about the variables and functions, if not MCVE.Barmak Shemirani
If the rectangle is small enough, isn't changing the cursor itself a good idea?sergiol

1 Answers

2
votes

You need to do your painting in your CView1::OnPaint method.

Also, you can use CDC::SetROP2 method using R2_NOTXORPEN instead of invalidating the entire window, this link has an example.