簡體   English   中英

在 CDialog 構造函數 [win32/MFC] 中創建 MFC 控件

[英]Create MFC controls in CDialog constructor [win32/MFC]

我正在開發包含一些 MFC 類和方法的庫。 我希望用戶能夠使用CDialogEx中的模板動態創建 CDialogEx。 對於模態對話框,我調用CDialog::InitModalIndirect ,然后調用CDialog::DoModal 對於無模式對話框,我調用CDialog::CreateIndirect然后CWnd::Show

代碼看起來像這樣:

// inside my library
class MyDialog : public CDialogEx
{
public:
    MyDialog(CWnd* parent) : CDialogEx()
    {
        parent_ = parent;
        my_template_data_ = CreateSomeGenericTemplate();
        // OnInitDialog should be preferably called here
    }

    void ShowModal()
    {
        InitModalIndirect(my_template_data_, parent_);
        DoModal(); // but it's called here - too late
    }

    void ShowModeless()
    {
        CreateIndirect(my_template_data_, parent_);
        Show(); // but it's called here - too late
    }

    MyButton* GetButton(int id)
    {
        // returns the instance of my MyButton, which is a subclassed CButton
    }

private:
    BOOL MyDialog::OnInitDialog() override
    {
        CDialogEx::OnInitDialog();
        
        // CWnd::Create for the UI controls can only be called here
    }
};

// user's code
// user creates the dialog - in the constructor it's not clear if modal or modeless
1. MyDialog user_dialog(some_parent); // here, I need the controls to be created
2. user_dialog.GetButton(42)->SetWindowText(L"new text"); // user wants to initialize his controls
// but he can't, because MyButton::Create was not called yet
3. user_dialog.ShowModal(); // and only then display the dialog
//by default, here the MFC calls OnInitDialog - too late,
//the SetText method needed to be set on line 2.

我的問題是,對話框的控件(按鈕等)只能在CDialog::OnInitDialog方法中創建,該方法在DoModal (用於模式)/ Show (用於無模式)方法之后自動調用。 我需要最好在構造函數中創建和正確初始化控件(使用CWnd::Create方法)。 我考慮過直接在構造函數中調用Show / DoModal ,但我還不知道它是模態對話框還是非模態對話框。 有解決辦法嗎? 提前謝謝了。

為什么不重構代碼並將公共代碼放在InitUI()方法中並從雙方調用它?

並且不要在構造函數上初始化接口。 OnInitDialog中進行模態; 並在CreateOnCreate (這意味着ON_WM_CREATE() map 條目)用於無模式對話框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM