CStatic not receiving WM_CTLCOLOR

2019-06-05 05:16发布

问题:

I think I am missing something small here.

I am trying to make a class which inherits from CStatic with a transparent background. I have managed create an instance of the class and it is displayed in the parent CView. However when I add a OnCtlColor message handler going through the class view on Visual Studio to make the background transparent, it never fires.

Here is a code snippet:

Foo.h

class Foo: public CStatic
{
    DECLARE_DYNAMIC(Foo)

public:
    Foo();
    virtual ~Foo();
    virtual void CreateCtrl(CWnd * Parent, POINT TopLeft, SIZE sz);

protected:
    DECLARE_MESSAGE_MAP()
public: 
    afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
    afx_msg BOOL OnEraseBkgnd(CDC* pDC);
};

Foo.cpp

void Foo::CreateCtrl(CWnd * Parent, POINT TopLeft, SIZE sz)
{
    CRect Rect(TopLeft, sz);
    Create(pItem->Value->GetBuffer(), WS_CHILD | WS_VISIBLE | SS_CENTER | SS_NOTIFY, Rect, Parent);
    ShowWindow(SW_SHOW);
}

BEGIN_MESSAGE_MAP(Foo, CStatic) 
    ON_WM_CTLCOLOR_REFLECT()
    ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

HBRUSH Foo::CtlColor(CDC* pDC, UINT nCtlColor)
{
    pDC->SetBkMode(TRANSPARENT);
    return (HBRUSH)GetStockObject(NULL_BRUSH);
}

BOOL Foo::OnEraseBkgnd(CDC* pDC)
{
    return FALSE;
}

Can anyone suggest what I might be doing wrong?

回答1:

WM_CTLCOLOR is sent to the parent window, not to the static control.

To catch the message in the static control class, you need to use ON_WM_CTLCOLOR_REFLECT in your message map, see MSDN Docs and use HBRUSH Foo::CtlColor(CDC* pDC, UINT nCtlColor).