现在的位置: 首页 > 综合 > 正文

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

2013年12月03日 ⁄ 综合 ⁄ 共 1636字 ⁄ 字号 评论关闭

参考: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(),获取父窗口

HWND hWnd = AfxGetMainWnd()->GetSafeHwnd();
if (MessageBox(hWnd, _T("是否继续"), _T("提示"), MB_OKCANCEL) == IDOK)
{
   ...;

}

 

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

 

 

 

抱歉!评论已关闭.