在子类 CStatic 控件中处理 WM_PAINT

2022-01-12 00:00:00 c++ mfc ownerdrawn wm-paint

我创建了一个自定义控件,其类以 CStatic 作为基类.目前我使用 WM_PAINT 事件处理绘图.但是有一个奇怪的行为.当我使用 CWnd::EnableWindow 函数禁用它后重新启用窗口时,它拒绝绘制我在 OnPaint 函数中编写的内容.它改为绘制静态控件.

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.

我同意有这种覆盖 DrawItem 并使用 SS_OWNERDRAW 样式的标准方法.但是 WM_PAINT 有什么问题?

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**
}

推荐答案

这正是我写的:

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));
}

和子类化:

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


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

   my_static.SubclassDlgItem(IDC_DRAW, this);

   return true;
}

IDC_DRAW 是此对话框资源的静态控件.我写了两个按钮处理程序:

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();
}

而且它完美无瑕!删除 Invalidate 调用会失败.

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

相关文章