HBRUSH data member initialization in OnInitDialog()
I have instructions to declare data members of type HBRUSH and then initialize them in OnInitDialog(). Then I should use these data members in HBRUSH CMyDialog::OnCtlColor(...) so I can change the background color and control colors for my dialog. My questions is: What does it mean to initialize the HBRUSH data members in OnInitDialog()? Thanks in advance.
Re: HBRUSH data member initialization in OnInitDialog()
When you declare data member of type HBRUSH you don't create a brush itself. In OnInitDialog you must create a brush using brush-creating functions like CreateBrushIndirect, CreateSolidBrush etc.
You can think about HBRUSH as about pointer - initially it's null and it will be null until you create a brush (analog of 'new' for pointers).
And like with pointers you must also destroy brush when you dialog is about to die (analog of 'delete' for pointers).
Good luck
Please rate if you think this response was useful for you
Have more questions? Feel free to ask.
Re: HBRUSH data member initialization in OnInitDialog()
Here are my notes on WM_CTLCOLOR. I use CBrush
instead of HBRUSH.
Here is a method for changing the text and/or background
color of some controls using the WM_CTLCOLOR message.
(edit,static,listbox,radio button,check button,dialog).
See WM_CTLCOLOR for more details.
1) add member variables for the dialog :
COLORREF m_textColor;
COLORREF m_backColor;
CBrush m_backBrush;
2) initialize in OnInitDialog() :
m_textColor = RGB(255,0,0);
m_backColor = RGB(192,192,0);
m_backBrush.CreateSolidBrush(m_backColor);
3) process WM_CTLCOLOR message for dialog :
HBRUSH CTestDialogDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
//
// note to change ALL the edit boxes, and not
// just one, the if statement below would be :
//
// if (nCtlColor == CTLCOLOR_EDIT)
//
// see WM_CTLCOLOR for more details
//
if (pWnd->GetDlgCtrlID() == IDC_EDIT1)
{
pDC->SetTextColor(m_textColor);
pDC->SetBkColor(m_backColor);
return (HBRUSH)m_backBrush.GetSafeHandle();
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
4) if at some time you want to change the colors,
code it like this :
m_textColor = RGB(255,255,0);
m_backColor = RGB(0,0,255);
m_backBrush.DeleteObject(); // delete old brush
m_backBrush.CreateSolidBrush(m_backColor); // and create new one
GetDlgItem(IDC_EDIT1)->Invalidate(); // force redraw of control
5) note : if you sub-class CEdit, you can do the
above in the derived class itself (process =WM_CTLCOLOR).
That way you do not have to check for the correct control ID.
Just be sure to return a non-NULL brush or the parent will
override the color.
Re: HBRUSH data member initialization in OnInitDialog()
Re: HBRUSH data member initialization in OnInitDialog()