我在对话框上放一个按钮,重载一个CButton类来关联这个按钮,然后发现每次在按钮上面点击鼠标的时候,都会收到一个WM_CTRLCOLOR消息。这个消息响应函数一般用来做什么?

解决方案 »

  1.   

    你写错了是WM_CTLCOLOR消息,MSDN上有说明的
    Most controls send this message to their parent (usually a dialog box) to prepare the pDC for drawing the control using the correct colors. To change the text color, call the SetTextColor member function with the desired red, green, and blue (RGB) values. To change the background color of a single-line edit control, set the brush handle in both the CTLCOLOR_EDIT and CTLCOLOR_MSGBOX message codes, and call the CDC::SetBkColor function in response to the CTLCOLOR_EDIT code. OnCtlColor will not be called for the list box of a drop-down combo box because the drop-down list box is actually a child of the combo box and not a child of the window. To change the color of the drop-down list box, create a CComboBox with an override of OnCtlColor that checks for CTLCOLOR_LISTBOX in the nCtlColor parameter. In this handler, the SetBkColor member function must be used to set the background color for the text. 
      

  2.   


    可是,既然SetBkColor和SetTextColor是可以在OnPaint里面去调用的,为什么要烦劳在CtlColor函数里面调用呢?而且我发现,只有向父窗口的反射函数CtlColor被调用了,按钮控件本身的OnCtlColor并没有被调用。
    问题来了,这个CtlColor函数里面的pDC是父窗口的,用它来设置SetBkColor并不能改变按钮控件本身的字体背景色。我把重载函数写成了:HBRUSH MyButton::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
    {
        // TODO:  Change any attributes of the DC here
     pDC->SetBkColor(RGB(255, 0, 0));
     CString str("hello");
     pDC->TextOut(20, 20, str);    TRACE(__FUNCTION__);
        f();    // TODO:  Return a non-NULL brush if the parent's handler should not be called
        return NULL;
    }运行后发现,Hello这个字符串被画到了对话框上面,如果改成TextOut(0,0,str),那么字符串就被按钮给挡住了.
      

  3.   

    还有,这句话让我非常不解:"Most controls send this message to their parent (usually a dialog box) to prepare the pDC for drawing the control using the correct colors.  "按钮为什么要向对话框发送这个消息,难道按钮是被对话框绘制的,而不是按钮自己通过OnPaint绘制的?
      

  4.   

    一般情况下,不要在WM_PAINT中调用SetBkColor和SetTextColor。
    在WM_PAINT中,应该调用GetBkColor和GetTextColor来得到颜色后,绘制到界面上。
      

  5.   

    我的问题在于,我发现这个SetBkColor是设置了父窗口(对话框)的问题背景颜色,而不是按钮控件本身的文字北京颜色。这到底是为什么?
      

  6.   

    Most controls send this message to their parent 
    父窗口收到该消息
    按钮 谁给它发这个消息 不调用不是很正常么?不知道你的有什么问题
    你查下CWnd::OnCtlColor  msdn上有个修改 静态框 的例子