AfxGetMainWnd()函数使用心得

版权声明:原创博文,转载请注明出处! https://blog.csdn.net/sunriver2000/article/details/81216960

关于AfxGetMainWnd()函数的通常认识:

1、使用AfxGetMainWnd()函数获取MFC程序中的主框架类指针是一个常用作法。

2、获得应用程序主窗口的指针的方法,AfxGetMainWnd()->m_hWnd或者AfxGetMainWnd()->GetSafeHwnd()。

但是,在用户线程中调用AfxGetMainWnd()函数好像就不灵了,为什么?

调试如下程序,按“F11”跟踪进去。

inline CEzCadToolDlg * GetDlg()
{
    return (CEzCadToolDlg *)AfxGetMainWnd();
}

看到该函数是这么Microsoft实现的。首先得调用AfxGetThread()函数,获取当前线程的句柄,然后调用GetMainWnd()函数。

_AFXWIN_INLINE CWnd* AFXAPI AfxGetMainWnd()
	{ CWinThread* pThread = AfxGetThread();
		return pThread != NULL ? pThread->GetMainWnd() : NULL; }

这么看来,AfxGetMainWnd()函数获取的句柄与所在线程关系紧密。

查阅MSDN,有如下阐述:

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.

如果 AfxGetMainWnd是从应用程序的主线程调用,它根据上述规则将返回应用程序的主窗口。如果该函数从应用程序的辅助线程调用,则该函数返回主窗口与执行调用的线程

红色部分是重点。MSDN官网翻译的不是很好啊(机器翻译吗?)。

实验:

应用程序启动一个线程,如下:

m_pAcptThread = AfxBeginThread(AcptThread, &m_si, THREAD_PRIORITY_NORMAL, 0, 0, 0);

在线程中调用AfxGetMainWnd()函数,

m_ci.p = AfxGetMainWnd();

调试信息如下,一目了然。

结论:在用户线程中调用AfxGetMainWnd()函数,获取的不是应用程序主框架类指针,而是线程的m_pMainWnd。

猜你喜欢

转载自blog.csdn.net/sunriver2000/article/details/81216960