【问题标题】:Create MFC controls in CDialog constructor [win32/MFC]在 CDialog 构造函数中创建 MFC 控件 [win32/MFC]
【发布时间】:2020-11-20 00:29:07
【问题描述】:

我正在开发包含一些 MFC 类和方法的库。我希望用户能够使用内存中的模板动态创建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,但我还不知道它是模态对话框还是无模态对话框。有解决办法吗?非常感谢。

【问题讨论】:

    标签: c++ winapi mfc win32gui cdialog


    【解决方案1】:

    你为什么不重构你的代码,把公共代码放在一个InitUI()方法中,从两边调用呢?

    并且不要在构造函数上初始化接口。在OnInitDialog 中执行模态;在CreateOnCreate(这意味着ON_WM_CREATE() 映射条目)中用于无模式对话框。

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多