Handling WM_PAINT in a Subclassed CStatic Control

2019-01-29 08:01发布

问题:

I created a custom control whose class has CStatic as base class. Currently I handle the drawing using WM_PAINT event. But there is a strange behavior. When I re-enable the window after disabling it using CWnd::EnableWindow function, it refuses to draw what I written in OnPaint function. It draws the static control instead.

I agree that there is this standard method of overriding DrawItem and using SS_OWNERDRAW style. But what's wrong with WM_PAINT?

void XXControl::OnPaint()
{
    CPaintDC PaintDC( this );
    // ** draw the control to PaintDC**
}

回答1:

Here is exactly what I have written:

class CMyStatic : public CStatic
{
    DECLARE_MESSAGE_MAP()
public:
    void OnPaint(void);
};

BEGIN_MESSAGE_MAP(CMyStatic, CStatic)
    ON_WM_PAINT()
END_MESSAGE_MAP()

void CMyStatic::OnPaint(void)
{
    CPaintDC dc(this);
    CRect rect;
    GetClientRect(&rect);

    dc.FillSolidRect(&rect, RGB(120,255,0));
}

And subclassed:

class CMyDlg : public CDialog
{
// Construction
    CMyStatic my_static;
...
};


BOOL CCMyDlg::OnInitDialog()
{
   CDialog::OnInitDialog();

   my_static.SubclassDlgItem(IDC_DRAW, this);

   return true;
}

Where IDC_DRAW is static control on resource for this dialog. I wrote two button handlers:

void CMyDlg::OnBnClickedOk()
{
    my_static.EnableWindow(FALSE);
    my_static.Invalidate();
}

void CMyDlg::OnBnClickedOk2()
{
    my_static.EnableWindow();
    my_static.Invalidate();
}

And it works flawlessly! Remove Invalidate call and it would fail.



回答2:

Try turning off Aero. I'm having a similiar problem where I'm drawing a static control and when it goes from disabled to enabled the WM_PAINT message is never received, but if I turn Aero off it works fine.