改變按鈕的背景色OnCtlColor,why?

有關OnCtlColor的說明MSDN中解釋如下:

Most controls send this message to their parent (usually a dialog box) to prepare thepDC 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 theCTLCOLOR_EDIT and CTLCOLOR_MSGBOX message codes, and call theCDC::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 aCComboBox with an override of OnCtlColor that checks forCTLCOLOR_LISTBOX in the nCtlColor parameter. In this handler, theSetBkColor member function must be used to set the background color for the text.

Note

This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

但在實際應用中,你卻可以發現並不能改變按鈕的背景色!!代碼如下:

HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
	// TODO: Change any attributes of the DC here 
	if (pWnd->GetDlgCtrlID() == IDC_BUTTON_1) //爲什麼這裏無法改變按鈕顏色??  
         //此處就算是按照MSDN中 nCtlColor == CTLCOLOR_BTN 也是不行哦。
	{
		pDC-> SetTextColor(RGB(15,5,200));
	}
	return hbr; // TODO: Return a different brush if the default is not desired
}


暫時無解?google上不了,先mark一下了。

百度上的搜索結果是需要自己重載CButton的DrawItem。還是使用CButtonST吧。

有關UI的那些事。。。。。。還是轉向QT啦。

嘿嘿,既然吃不了荷包蛋,就該喫蛋炒飯吧,何必去追求雞爲何不會下鴨蛋呢!

附上DrawItem的source code:設定按鈕的文本顏色爲藍色!

void MyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct )
{
	// TODO:  Add your code to draw the specified item
	UINT uStyle = DFCS_BUTTONPUSH;

	// This code only works with buttons.
	ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);

	// If drawing selected, add the pushed style to DrawFrameControl.
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
		uStyle |= DFCS_PUSHED;

	// Draw the button frame.
	::DrawFrameControl(lpDrawItemStruct->hDC, &lpDrawItemStruct->rcItem, 
		DFC_BUTTON, uStyle);

	// Get the button's text.
	CString strText;
	GetWindowText(strText);

	// Draw the button text using the text color red.
	COLORREF crOldColor = ::SetTextColor(lpDrawItemStruct->hDC, RGB(0,0,255));
	::DrawText(lpDrawItemStruct->hDC, strText, strText.GetLength(), 
		&lpDrawItemStruct->rcItem, DT_SINGLELINE|DT_VCENTER|DT_CENTER);
	::SetTextColor(lpDrawItemStruct->hDC, crOldColor);

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章