Something for a child window analogous to `this`

2019-08-20 15:57发布

问题:

I am a newcomer to programming. I am writing a dialog based application which has a static control on it. Using

Using
void CMy1stDlg::OnMouseMove(UINT nFlags, CPoint point)
{
    if (this == GetCapture())
    {
        CClientDC aDC(this);
        aDC.SetPixel(point, RGB(255,0,0));
    }   
}

I can create results like

However what I want is that the locus of mouse is only drawn within the static window. I can't find the reference to this in MSDN and I don't know why the following method fails.

void CMy1stDlg::OnMouseMove(UINT nFlags, CPoint point)
{
    CWnd* pMYSTATIC = GetDlgItem (IDC_MYSTATIC);    //IDC_MYSTATIC is the ID of the static control
    if (pMYSTATIC == GetCapture())
    {
        CClientDC aDC(pMYSTATIC);
        aDC.SetPixel(point, RGB(255,0,0));
    }   
}

How can I get what I want? Are there any methods to get something for the static window analogous to this? I will appreciate any help with these.

回答1:

OK, try this:

void CMy1stDlg::OnMouseMove(UINT nFlags, CPoint point)
{
    CRect rect;
    // Get static control's rectangle
    GetDlgItem(IDC_MYSTATIC)->GetWindowRect(&rect);
    // Convert it to client coordinates
    ScreenToClient(&rect);
    // Check if mouse pointer is inside the static window, if so draw the pixel
    if (rect.PtInRect(point))
    {
        CClientDC dc(this);
        dc.SetPixel(point.x, point.y, RGB(255,0,0));
    }
}

This code may need some fixes too, eg shrink the rectangle (to its client-only area), before checking whether to draw the pixel.

Please note that you don't need to check GetCapture(); if your dialog hasn't captured the mouse it won't be receiving this message anyway.

Also, all these functions are wrappers of Windows SDK ones, eg the ClientDC() class, basically wraps GetDC()/ReleaseDC().