我可以从对话框的 DoModal 函数返回自定义值吗?

2022-01-12 00:00:00 windows return-value winapi c++ mfc

我想要做的是,在使用 DoModal() 创建一个对话框并在框中按 OK 退出它之后,返回一个自定义值.例如,用户将在对话框中输入的几个字符串.

What I wish to do is, after creating a dialog box with DoModal() and pressing OK in the box to exit it, to have a custom value returned. For example, a couple of strings the user would input in the dialog.

推荐答案

你不能改变DoModal()函数的返回值,即使可以,我也不推荐它.这不是这样做的惯用方式,如果您将其返回值更改为字符串类型,您将无法查看用户何时取消对话框(在这种情况下,返回的字符串值应该完全忽略).

You can't change the return value of the DoModal() function, and even if you could, I wouldn't recommend it. That's not the idiomatic way of doing this, and if you changed its return value to a string type, you would lose the ability to see when the user canceled the dialog (in which case, the string value returned should be ignored altogether).

相反,向对话框类添加另一个(或多个)函数,例如 GetUserName()GetUserPassword,然后在 DoModal 返回 IDOK.

Instead, add another function (or multiple) to your dialog box class, something like GetUserName() and GetUserPassword, and then query the values of those functions after DoModal returns IDOK.

例如,显示对话框和处理用户输入的函数可能如下所示:

For example, the function that shows the dialog and processes user input might look like this:

void CMainWindow::OnLogin()
{
    // Construct the dialog box passing the ID of the dialog template resource
    CLoginDialog loginDlg(IDD_LOGINDLG);

    // Create and show the dialog box
    INT_PTR nRet = -1;
    nRet = loginDlg.DoModal();

    // Check the return value of DoModal
    if (nRet == IDOK)
    {
        // Process the user's input
        CString userName = loginDlg.GetUserName();
        CString password = loginDlg.GetUserPassword();

        // ...
    }
}

相关文章