MFC 自定義控件


 

需要在MFC實現自定義控件功能,網上搜集找的如下方法實現:

以下是步驟說明。

       一、自定義一個空白控件

       1、先創建一個MFC工程

       NEW Project-->MFC-->MFC Application-->name:  “CustomCtr”-->Application 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);   
}  

 以上是自定義一個空白控件。
 
       二、在控件上繪圖

       1、在CMyTest類中添加一個繪圖消息

       在VS2010最左側Class View中右擊CMyTest類-->ClassWizard-->Messages-->WM_PAINT-->雙擊,開發環境自動添加OnPaint()函數及消息隊列。

       2、編寫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); } 

 

來自:http://6208051.blog.51cto.com/6198051/1058634

參考:http://blog.csdn.net/worldy/article/details/16337139


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM