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.
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).
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();
// ...
}
}
I was looking for an answer and agree that in most cases that you would not change the standard behavior of a dialog. But there might be a case where you would like to pick what the user is actually responding say if you had several buttons and want specifically that they picked the OK at the top versus the OK at the bottom. You know for metrics.
Or say if you wanted to have slightly different results if the dialog caused an error when running on of your functions. It would be nice to return a value that is not IDOK but maybe some other value.
I found Dialog::EndDialog()
with details and an example of usage here: MSDN: Dialog::EndDialog
#include "ANewDialog.h"
void CMyWnd::ShowDialog()
{
CMyDialog myDlg;
int nRet = myDlg.DoModal();
if ( nRet == 18 )
AfxMessageBox("Dialog closed. But there was a problem.");
}
/* MyDialog.cpp */
void CMyDialog::OnSomeButtonAction()
{
int nRet = 0;
// Run your function with return value;
nRet = YourReallyFunFunction();
EndDialog(nRet); // Set the return value returned by DoModal!
return; // The dialog closes and DoModal returns here!
}
I don't think it is possible (or reasonable). DoModal returns an INT_PTR, which is usually used to know what the user did to exit the dialog (press OK, Cancel, there was an error...). The way to do it is have public members or functions which the dialog set and the caller of the dialog can access to know the values. Like so:
CMyDialog dlg;
if(dlg.DoModal()==IDOK)
{
CString str1 = dlg.m_String1;
CString str2 = dlg.GetString2();
}
It's the way you would use CFileDialog, for example.
精彩评论