指定MessageBox所属父窗口(使用AfxGetMainWnd())

来源:互联网 发布:怎么才能做淘宝客服 编辑:程序博客网 时间:2024/06/06 12:18

参考:MSDN

通常情况下:我们在CDialog的内部函数中,不需要指定HWND;另外在许多调用的时候,我们可以获取到父窗口的指针。pMainWnd->GetSafeHwnd() 就可以了。


但在一些情况里:例如 回掉函数 中,我们可能无法获取所属的父窗口:

int MessageBox(  HWND hWnd,   LPCTSTR lpText,   LPCTSTR lpCaption,   UINT uType); 

 

当hWnd使用NULL的时候:If this parameter is NULL, the message box has no owner window.

该窗口不隶属于某个窗口,导致该探出MessageBox可能会放在别的窗口的后面,可能被遮挡。大多数情况,我们希望MessageBox像模态窗口一样,隶属于父窗口,恒位于调用窗口的前面。

 模态窗口说明:所谓模态对话框,就是指当这个对话框弹出的时候,鼠标不能单击这个对话框之外的区域,这种对话框往往是用户进行了某种操作后才出现的。

 

此时我们可以这样来做:使用AfxGetMainWnd(),获取父窗口

<span style="font-size:14px;">HWND hWnd = AfxGetMainWnd()->GetSafeHwnd();if (MessageBox(hWnd, _T("是否继续"), _T("提示"), MB_OKCANCEL) == IDOK)</span><pre class="cpp" name="code"><span style="font-size:14px;">{</span><pre class="cpp" name="code"><span style="font-size:14px;"></span><pre class="cpp" name="code"><pre class="cpp" name="code"><span style="font-size:14px;">   ...;</span>
}


 

AfxGetMainWnd返回值:

If your application is an OLE server, call this function to retrieve a pointer to the active main window of the application instead of directly referring to them_pMainWnd member of the application object.

 
CWnd* AFXAPI AfxGetMainWnd( );

 

If the server has an object that is in-place active inside a container, and this container is active, this function returns a pointer to the frame window object that contains the in-place active document.

If there is no object that is in-place active within a container, or your application is not an OLE server, this function simply returns them_pMainWnd of your application object.

If AfxGetMainWnd is called from the application's primary thread, it returns the application's main window according to the above rules. If the function is called from a secondary thread in the application, the function returns the main window associated with the thread that made the call.


 

 附加:

类似的,我们可以使用另外的一些其它MFC的全局的函数

CWinApp* AFXAPI <strong>AfxGetApp</strong>();                // 获取当前应用CWnd* AFXAPI <strong>AfxGetMainWnd</strong>();               // 获取主窗口HINSTANCE AFXAPI <strong>AfxGetInstanceHandle</strong>();    // 获取实例句柄HINSTANCE AFXAPI <strong>AfxGetResourceHandle</strong>();    // 获取资源句柄void AFXAPI <strong>AfxSetResourceHandle</strong>(HINSTANCE hInstResource); // 设置资源LPCTSTR AFXAPI <strong>AfxGetAppName</strong>();             // 获取应用名称


 

 Owed by: 春夜喜雨 http://blog.csdn.net/chunyexiyu  转载请标明来源