MFC 在代码中增加单选按钮
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MFC 在代码中增加单选按钮相关的知识,希望对你有一定的参考价值。
我需要编写一个程序,单选按钮从2个到6个,需要后期根据其他数据确定,请问可不可以在代码中添加单选按钮?难道必须先添加6个,然后通过visible属性来控制可见性吗?这样太麻烦了。求协助。谢谢。
在单文档类MFC中动态创建按钮:1)在view类中定义一个变量:
CButton m_MyBtn;
2)在view类中增加OnCreate消息处理函数
在该函数中增加按钮的创建代码:
m_MyBtn.Create("Open", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD, CRect(10, 10, 100, 35), this, 2001);
或者
CRect rect(50,50, 200,70);
m_MyBtn.Create("GetPath", WS_CHILD, rect, this, 2001);
m_MyBtn.ShowWindow(SW_SHOW);
3)创建按钮的按键消息映射
在view.cpp的
BEGIN_MESSAGE_MAP(CGetPathView, CView)
END_MESSAGE_MAP()
之间插入ON_BN_CLICKED(2001, OnMyBtnClick)
并为OnMyBtnClick函数进行声明及设计:
声明:在view.h文件中:
DECLARE_MESSAGE_MAP()
之前插入afx_msg void OnMyBtnClick();
函数体设计:
在view.cpp文件中插入:
void CGetPathView::OnMyBtnClick()
char Path[1000];
::GetModuleFileName(NULL,Path,1000);
CString StrPath;
StrPath.Format("当前应用程序路径为:%s",Path);
AfxMessageBox(StrPath);
动态创建单选按钮的方法和这个类似,仿造下就行了。 参考技术A 你可以用create函数来做,只要指定一个范围比较大的ID就好了,比如ID是1000到2000,那么你就可以创建大概2001个单选按钮。 参考技术B 先添加6个,然后通过visible属性来控制可见性这种方法是最好的,当然也可以动态创建。
猎豹MFC--对话框 复选框 单选按钮


使用单选按钮要注意:单选键按钮的顺序必须是连续的,如果不是连续的一定要调整一下
设置分组为true
初始化 默认值:打开源文件找到初始化对话框:
开始ID按钮到最后一个按钮 选中最后一个:
效果如下:

添加事件处理函数后在该函数内 填写失效函数:

失效后擦出背景:
选中矩形画矩形:


为绿色复选框添加变量代码:


调用上一个事件处理函数。


调用蓝色:



圆形设置也一样:

以上是关于MFC 在代码中增加单选按钮的主要内容,如果未能解决你的问题,请参考以下文章