您的位置:首页 > 其它

VS2010添加自定义控件

2015-04-20 13:57 211 查看


VS2010添加自定义控件

一:自定义一个空白控件

1 :先创建一个MFC工程

NEW Project-->MFC-->MFC Application-->name: CustomCtr-->Type选择“Dialog based”;











2: 在窗口中添加一个自定义控件

Toolbox-->“Custom Control”-->属性-->class随便填写一个控件类名“CMyWin”, 这个名字用于以后注册控件用的,注册函数 RegisterWindowClass();





3:创建一个类

在窗口中,右击custom control 控件-->ClassWizard-->ClassWizard-->Add Class-->类名CMyTest以C开头-->Base class:CWnd;



4:注册自定义控件MyWin

在MyTest类.h文件中声明注册函数BOOL RegisterWindowClass(HINSTANCE hInstance = NULL);

BOOL CMyTest::RegisterWindowClass(HINSTANCE hInstance)

{

LPCWSTR className = L"CMyWin";//"CMyWin"控件类的名字

WNDCLASS windowclass;

if(hInstance)

hInstance = AfxGetInstanceHandle();

if (!(::GetClassInfo(hInstance, className, &windowclass)))

{

windowclass.style = CS_DBLCLKS;

windowclass.lpfnWndProc = ::DefWindowProc;

windowclass.cbClsExtra = windowclass.cbWndExtra = 0;

windowclass.hInstance = hInstance;

windowclass.hIcon = NULL;

windowclass.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);

windowclass.hbrBackground = ::GetSysColorBrush(COLOR_WINDOW);

windowclass.lpszMenuName = NULL;

windowclass.lpszClassName = className;

if (!AfxRegisterClass(&windowclass))

{

AfxThrowResourceException();

return FALSE;

}

}

return TRUE;

}

5:在MyTest类的构造器中调用,RegisterWindowClass();

CMyTest::CMyTest()

{

RegisterWindowClass();

}

6:控件与对话框数据交换

在CustomCtrDlg.h中定义一个变量

CMyTest m_draw;

在对话框类的CustomCtrDlg.cpp的DoDataExchange函数中添加 DDX_Control(pDX,IDC_CUSTOM1,m_draw);

void CCustomCtrDlg::DoDataExchange(CDataExchange* pDX)

{

CDialogEx::DoDataExchange(pDX);

DDX_Control(pDX,IDC_CUSTOM1,m_draw);

}

以上是自定义一个空白控件。

二: 在控件上绘图

7: 在CMyTest类中添加一个绘图消息

在VS2010最左侧Class View中右击CMyTest类-->ClassWizard-->Messages-->WM_PAINT-->双击

开发环境自动添加OnPaint()函数及消息队列。



8:编写OnPaint()函数

例如:画一条直线

void CMykk::OnPaint()

{

CPaintDC dc(this); // device context for painting

// TODO: Add your message handler code here

// Do not call CWnd::OnPaint() for painting messages

CRect rect;

this->GetClientRect(rect);

dc.MoveTo(0,0);

dc.LineTo(rect.right,rect.bottom);

}

转自:/article/10427173.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: