[英]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
中进行模态; 并在Create
或OnCreate
(这意味着ON_WM_CREATE()
map 条目)用于无模式对话框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.