VC6 MFC 如何让用户选择颜色并显示在对话框内?

来源:互联网 发布:淘宝上显示广告的商品 编辑:程序博客网 时间:2024/05/22 10:53

1、效果展示

-----------------------------------------


2、实现方法

-----------------------------------------

1、打开Visual C++ 6.0,新建一个基于对话框的MFC程序,命名为Color,设计好程序界面:


2、修改控件ID:

                       “选择颜色”按钮:IDC_COLOR_BUTTON

                       “这是您选择的颜色”静态文本框:IDC_TEXT

                       “R”编辑框:IDC_R_EDIT

                       “G”编辑框:IDC_G_EDIT

                       “B”编辑框:IDC_B_EDIT

3、右键点击“R”编辑框,选择【属性】。

4、切换到“样式”(Style)选项卡。


5、把“只读”(Read Only)复选框勾选上。


6、分别右键点击其他两个编辑框,重复3-5步。

7、打开类向导,添加变量:

              IDC_R_EDIT:CEdit    m_r_edit

              IDC_G_EDIT:CEdit    m_g_edit

              IDC_B_EDIT:CEdit    m_b_edit


8、编辑对话框初始化函数OnInitDialog:

BOOL CColorDlg::OnInitDialog(){          // ... ...          // TODO: Add extra initialization here  m_r_edit.SetWindowText(_T("255"));  m_g_edit.SetWindowText(_T("0"));  m_b_edit.SetWindowText(_T("0"));          return TRUE;  // return TRUE  unless you set the focus to a control}


9、打开类向导,选择【Message Maps】选项卡,【Object IDs】列表框选择【CColorDlg】,【Messages】列表框选择【WM_CTLCOLOR】,点击【Add Function】,【Member functions】列表框选择【OnCtlColor】,点击【Edit Code】。


10、在OnCtlColor函数内插入代码:

// TODO: Change any attributes of the DC hereif(pWnd->GetDlgCtrlID()==IDC_TEXT){pDC->SetTextColor(colorDlg.GetColor()); //colorDlg是一个变量,在下一步会说明}


11、在ColorDlg.cpp文件中声明两个变量(具体位置请看图):

COLORREF color = RGB(255,0,0);CColorDialog colorDlg(color);


12、为“选择颜色”按钮添加处理程序OnColorButton,修改为:

void CColorDlg::OnColorButton() {// TODO: Add your control notification handler code hereif(colorDlg.DoModal()==IDOK)//如果用户在颜色对话框中点击了“确定”{color = colorDlg.GetColor();//获取颜色SetDlgItemInt(IDC_R_EDIT,GetRValue(color));//获取R颜色显示在编辑框内SetDlgItemInt(IDC_G_EDIT,GetGValue(color));//获取G颜色显示在编辑框内SetDlgItemInt(IDC_B_EDIT,GetBValue(color));//获取B颜色显示在编辑框内}Invalidate(TRUE);//最重要的一句代码,重绘窗口}

13、如果想让程序的界面跟随系统主题变化,可以参考http://blog.csdn.net/baidu_38494049/article/details/76276895

14、编译程序,运行程序,看到效果!默认颜色为红色,可以通过按钮重新选择颜色。





感谢http://www.jizhuomi.com/school/c/168.html提供的部分源代码!

阅读全文
0 0
原创粉丝点击