Visual Studio .NET 2002Windows VistaVisual Studio .NET 2003Windows 2003Windows 2000Visual C++ 6.0Windows XPMFC初学者开发Visual StudioWindowsC++
彩色按钮






1.15/5 (20投票s)
2006年10月18日
1分钟阅读

113823

3087
更改按钮控件的颜色
引言
本教程是一个绘制自定义按钮控件的逐步过程。本教程是关于重新绘制按钮控件的。
1. 打开 AppWizard 并创建一个名为 btncolor 的新项目。只需创建一个基本的对话框,无需任何文档/视图架构。
2. 然后点击“工作区”窗口中的 ResourceVew 选项卡。继续编辑对话框 IDD_BTNCOLOR_DLG。它已经包含按钮“确定”和“取消”。删除“TODO :”消息和取消按钮。
3. 拖放所需的按钮,在本例中为“颜色”。然后选择并右键单击以编辑其属性。MFC 通过其唯一的 ID(位于“Resource.h”文件中的宏)跟踪这些按钮。为了代码清晰,将 ID 的名称更改为 IDC_BUTTON_COLOR 并修改按钮的标题。
4. 将按钮的样式更改为 OwnerDraw。
5. 现在我们的按钮已经就位,我们需要将它们连接到我们的应用程序。我们通过类向导来完成此操作。(Control + W)点击“成员变量”选项卡。
6. 为 CBtnColorDlg 添加消息映射条目 WM_DRAWITEM。并按照以下所示编辑 OnDrawItem 代码。
void CBtncolorDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) { // TODO: Add your message handler code here and/or call default if(nIDCtl==IDC_BUTTON_COLOR) //checking for the button { CDC dc; RECT rect; dc.Attach(lpDrawItemStruct ->hDC); // Get the Button DC to CDC rect = lpDrawItemStruct->rcItem; //Store the Button rect to our local rect. dc.Draw3dRect(&rect,RGB(255,255,255),RGB(0,0,0)); dc.FillSolidRect(&rect,RGB(100,100,255));//Here you can define the required color to appear on the Button. UINT state=lpDrawItemStruct->itemState; //This defines the state of the Push button either pressed or not. if((state & ODS_SELECTED)) { dc.DrawEdge(&rect,EDGE_SUNKEN,BF_RECT); } else { dc.DrawEdge(&rect,EDGE_RAISED,BF_RECT); } dc.SetBkColor(RGB(100,100,255)); //Setting the Text Background color dc.SetTextColor(RGB(255,0,0)); //Setting the Text Color TCHAR buffer[MAX_PATH]; //To store the Caption of the button. ZeroMemory(buffer,MAX_PATH ); //Intializing the buffer to zero ::GetWindowText(lpDrawItemStruct->hwndItem,buffer,MAX_PATH); //Get the Caption of Button Window dc.DrawText(buffer,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);//Redraw the Caption of Button Window dc.Detach(); // Detach the Button DC } CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct); }
完成了!构建代码并运行它。