最近使用VS2010 C++中的CMFCPropertyGridCtrl控件,记录如下
1.PropertyGrid控件的基本使用
2.控件响应消息
3.添加选择属性
4.实现颜色,字体,文件属性
1. PropertyGrid控件的基本使用(基于对话框)
(1)创建一对话框,将CMFCPropertyGridCtrl控件拖入对话框中
(2)使用向导,在头文件中创建控件变量:CMFCPropertyGridCtrl m_gridCtrl;
(3)在对话框的初始化函数中(OnInitDialog()),添加如下代码:
...
//指定显示头
m_gridCtrl.EnableHeaderCtrl(TRUE, _T("属性"), _T("值"));
//指定列宽
HDITEM item;
item.cxy=120;
item.mask=HDI_WIDTH;
m_gridCtrl.GetHeaderCtrl().SetItem(0, new HDITEM(item));
//建立属性
m_gridGroup = new CMFCPropertyGridProperty(_T("分辨率"));
m_gridGroup->AddSubItem(new CMFCPropertyGridProperty(_T("宽度"), _T("1024"), _T("单位:像素")));
m_gridGroup->AddSubItem(new CMFCPropertyGridProperty(_T("高度"), _T("768" ), _T("单位:像素")));
CString describeText = _T("双击[其它]弹出对话框,查看或编辑其它的属性");
CMFCPropertyGridProperty* pItem2 = new CMFCPropertyGridProperty(_T("其它"), _T("<--点击查看编辑"), describeText);
pItem2->AllowEdit(FALSE);
m_gridGroup->AddSubItem(pItem2);
//将属性添加到控件中
m_gridCtrl.AddProperty(m_gridGroup);
... ...
(4)编译执行如下图所示:
2. 响应鼠标消息
例如:有的属性难以用文字描述,需要图文并茂展示出来。
(1)使用类向导创建一个派生于CMFCPropertyGridCtrl的类
class CMyGridCtrl : public CMFCPropertyGridCtrl
{
DECLARE_DYNAMIC(CMyGridCtrl)
public:
CMyGridCtrl();
virtual ~CMyGridCtrl();
protected:
DECLARE_MESSAGE_MAP()
};
(2)将控件变量重新定义为:CMyGridCtrl m_gridCtrl;
(3)对派生的CMyGridCtrl的类添加左键双击函数,并对函数进行实现
void CMyGridCtrl::OnLButtonDblClk(UINT nFlags, CPoint point)
{
SetFocus();
CMFCPropertyGridProperty::ClickArea clickArea;
CMFCPropertyGridProperty* pHit = HitTest(point, &clickArea);
switch (clickArea)
{
case CMFCPropertyGridProperty::ClickExpandBox:
break;
case CMFCPropertyGridProperty::ClickName:
{
CString tip = pHit->GetName();
if(tip == _T("其它"))
{
COtherPropertyDlg dlg;
dlg.DoModal();
}
}
break;
case CMFCPropertyGridProperty::ClickValue:
break;
default:
break;
}
CMFCPropertyGridCtrl::OnLButtonDblClk(nFlags, point);
}
(4)编译,执行程序如下:
3.添加选择属性
//添加选择属性
describeText = _T("选择型号 i7,i5,i3");
CMFCPropertyGridProperty* pProp2 = new CMFCPropertyGridProperty(_T("CPU型号"), _T("i5"), describeText);
pProp2->AddOption(_T("i7"));
pProp2->AddOption(_T("i5"));
pProp2->AddOption(_T("i3"));
pProp2->AllowEdit(FALSE); //不允许对选项进行编辑
m_gridCtrl.AddProperty(pProp2);
4.添加选择颜色,字体,文件属性
//颜色
CMFCPropertyGridColorProperty* pProp3 = new CMFCPropertyGridColorProperty(_T("机箱颜色"), RGB(0, 0, 0));
m_gridCtrl.AddProperty(pProp3);
//文件
CMFCPropertyGridFileProperty * pProp4 = new CMFCPropertyGridFileProperty(_T("配置文件"), TRUE, _T("D:\\test.cfg"));
m_gridCtrl.AddProperty(pProp4);
//获得当前字体
HFONT hFont=(HFONT)GetStockObject(SYSTEM_FONT);
LOGFONT logFont={0};
GetObject(hFont,sizeof(logFont),&logFont);
DeleteObject(hFont);
CMFCPropertyGridFontProperty * pProp5 = new CMFCPropertyGridFontProperty(_T("选择字体"), logFont);
m_gridCtrl.AddProperty(pProp5);
选择属性而不是表示值,属性项可以启动允许用户选择颜色、文件或字体的对话框。
下表列出了四个选择属性类型:
类 | 说明 |
---|---|
用于指定字符串的值的泛型属性,对于布尔值,日期等。 | |
用于选择颜色值的属性。 | |
用于选择文件的属性。 | |
用于选择字体的属性。 |