MFC 手動添加控件

您可以使用對話框編輯器向對話框中添加控件或者通過代碼自己添加控件。


若要自己創建控件對象,通常要將 C++ 控件對象嵌入 C++ 對話框或框架窗口對象。與框架中的許多其他對象一樣,控件也需要兩步構造。作爲創建父對話框或框架窗口的一部分,應調用控件的 Create 成員函數。對於對話框,這通常在 OnInitDialog 中完成;對於框架窗口,則通常在 OnCreate 中完成。


下面的示例顯示如何在派生對話框類的類聲明中聲明 CEdit 對象,然後調用 OnInitDialog 中的 Create 成員函數。由於 CEdit 對象被聲明爲嵌入對象,它將在對話框對象構造時自動構造,但仍必須用它自己的 Create 成員函數初始化。


class CMyDialog : public CDialog
{
protected:
    CEdit m_edit;   // Embedded edit object
public:
    virtual BOOL OnInitDialog();
};
下列 OnInitDialog 函數設置一個矩形,然後調用 Create 以創建 Windows 編輯控件 (Edit Control) 並將其附加到未初始化的 CEdit 對象。


BOOL CMyDialog::OnInitDialog()
{
    CDialog::OnInitDialog();
    CRect rect(85, 110, 180, 210);


    m_edit.Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP |
             ES_AUTOHSCROLL | WS_BORDER, rect, this, 2); 
    m_edit.SetFocus();
    return FALSE;
}

創建編輯對象後,還可以通過調用 SetFocus 成員函數設置控件的輸入焦點。最後從 OnInitDialog 返回 0,說明設置了焦點。如果返回非零值,對話框管理器將焦點設置爲對話框項列表中的第一個控件項。


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

CWnd::Create

窗口創建函數。指定父窗口的指針,將自己覆蓋到父窗口上面。
virtual BOOL Create(
   LPCTSTR lpszClassName,
   LPCTSTR lpszWindowName,
   DWORD dwStyle,
   Const RECT& rect,
   CWnd* pParentWnd,
   UINT nID,
   CCreateContext* pContext = NULL
);


Parameters
[in] lpszClassName 窗口類名
[in] lpszWindowName 窗口標題
[in] dwStyle 窗口類型
[in] rect 窗口在父窗口上面的位置,相對父窗口。
[in] pParentWnd 父窗口的指針
[in] nID 窗口的ID(類似Tag,用以區分父窗口中其他的子窗口)
[in] pContext Pointer to a CCreateContext structure that is used to customize the document-view architecture for the application.


Return Value
成功返回true,失敗返回false


CToolBar::LoadToolBar
調用該成員函數的加載 lpszResourceName 或 nIDResource指定的工具欄。


BOOL LoadToolBar(
   LPCTSTR lpszResourceName 
);
BOOL LoadToolBar(
   UINT nIDResource 
);


參數
lpszResourceName
對要加載的工具欄的資源名稱的指針。
nIDResource
要加載的工具欄的資源 ID。


返回值
非零,如果成功;否則爲 0。



發佈了18 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章