MFC 模態對話框dlg.DoModal()返回值

查了很多資料,都說DoModal()返回值爲OK或CANCEL鍵的ID

 

  其實,這種說法是錯誤的

 

  MSDN是這樣說明其返回值的

 

        If successful, the value of the nRetCode parameter specified in the call toEndDialog; otherwise, -1.

 

        如果操作成功,其返回值爲由EndDialog指定的nRetCode的值,而此參數nRetCode的含義爲關閉對話框所採用的方式

  

     也就是說,在關閉此模態對話框時,其返回值爲關閉對話框時所採用的方式

     因此它只在對話框關閉時才返回相關參數值

 

     默認對話框關閉方式有2種:OnOK();    OnCancel()

 

     當使用OnOK()函數關閉對話框時,返回值爲IDOK

 

     當使用OnCancel()函數關閉對話框時,返回值爲IDCANCEL

 

     返回值與ID無關 

 

     比如一個按鈕的ID爲IDC_BUTTON1

     在此按鈕的處理函數中添加關閉對話框方式: OnOk()

     則 點擊此按鈕時,對話框返回值爲IDOK

 

 

除此兩種默認關閉方式外,還可用EndDialog(int nRetCode)設定自定義的關閉方式

 

如下例子:

 


[c-sharp] view plain copy

  1. void EndDialog(  

  2.    int nResult   

  3. );  

  4.   

  5. Parameters  

  6.   

  7. nResult  

  8.   

  9.     Contains the value to be returned from the dialog box to the caller of DoModal.  

  10.   

  11.  Remarks  

  12.   

  13. This member function returns nResult as the return value of DoModal. You must use the EndDialog function to complete processing whenever a modal dialog box is created.  

  14.   

  15. You can call EndDialog at any time, even in OnInitDialog, in which case you should close the dialog box before it is shown or before the input focus is set.  

  16.   

  17. EndDialog does not close the dialog box immediately. Instead, it sets a flag that directs the dialog box to close as soon as the current message handler returns.  

  18.   

  19.   

  20.   

  21.   

  22.   

  23.  Example  

  24.   

  25. /* MyWnd.cpp */  

  26. #include "MyDialog.h"  

  27.   

  28. void CMyWnd::ShowDialog()  

  29. {  

  30.    CMyDialog myDlg;  

  31.    int nRet = myDlg.DoModal();  

  32.   

  33.    if ( nRet == IDOK || nRet == 5  )  

  34.       AfxMessageBox("Dialog closed successfully");  

  35. }  

  36.   

  37. /* MyDialog.cpp */  

  38. void CMyDialog::OnSomeAction()  

  39. {  

  40.    // Do something  

  41.   

  42.    int nRet = 5; // Just any value would do!  

  43.    EndDialog(nRet); // This value is returned by DoModal!  

  44.   

  45.    // Do something  

  46.   

  47.    return// Dialog closed and DoModal returns only here!  

  48. }  


 

 

 

 

在工程中遇到這樣的問題

 

一個模態對話框 有三個按鈕

 

分別是ONOK()   ONCANCEL() EndDialog(0XFF)

 

   

但是發現 當按模態對話框右上角的叉號關閉對話框時

 

總是跳到ONCANCEL()關閉對話框時相同的處理方法

 

推斷:   點擊叉後 它默認也是ONCANCEL關閉窗口

 

 

解決方法:  因爲叉響應WM_COLOSE消息 因此爲它創建一個關閉方式

 

 


[c-sharp] view plain copy

  1. void WeiKuangKe::OnClose()  

  2. {  

  3.     // TODO: Add your message handler code here and/or call default     

  4.       

  5.         int nRet=5;  

  6.         EndDialog(nRet);  

  7.   

  8. }  


 

參考資料:

 

http://technet.microsoft.com/zh-cn/office/wddd3ztw%28VS.80%29.aspx

轉載自:http://blog.csdn.net/shuilan0066/article/details/5775383

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章