CWinThread::m_pMainWnd Remarks Use this data member to store a pointer to your thread’s main window object. The Microsoft Foundation Class Library will automatically terminate your thread when the window referred to by m_pMainWnd is closed. If this thread is the primary thread for an application, the application will also be terminated. If this data member is NULL, the main window for the application’s CWinApp object will be used to determine when to terminate the thread. m_pMainWnd is a public variable of typeCWnd*. Typically, you set this member variable when you override InitInstance. In a worker thread, the value of this data member is inherited from its parent thread. 用该成员变量去存储你的线程主窗口对象。当和m_pMainWnd 相关的窗口被关闭后,MFC会自动终止你的线程。如果该线程是应用程序主线程,程序也将会被终止。如果该数据成员为NULL,应用程序CWinApp对象的主窗口将用来决定什么时候去终止线程。m_pMainWnd是一个CWnd*类型的public变量。 系统自动生成的主窗口句柄.
CXXXXXDlg dlg; |
AfxGetApp()->m_pMainWnd
1: AfxGetApp()->m_pMainWnd这个东西就是主窗口的指针。即CMainFrame类的对象指针。很多东西的创建和它有关。以及可以用它来获取视图和文档指针。也可以使用AfxGetMainWnd();或 AfxGetApp()->GetMainWnd()
这个函数在程序的任何地方都可以调用的原因是它是一个全局函数,函数返回值是CWinApp * 。它将返回程序在进入WinMain()函数之前,系统就为程序创建好的一个CWinApp全局实例theApp,通过这个实例的成员变量m_pMainWnd便可以很容易地在程序地任何地方得到程序的主窗口指针。进而可以引用主窗口类的成员变量和成员函数。
CWinApp* AfxGetApp( );
A pointer to the single CWinApp object for the application.
The pointer returned by this function can be used to access application information such as the main message-dispatch code or the topmost window.
返回值:指向应用程序的单一CWinApp对象的指针。
说明:
这个函数返回的指针可以被用来访问应用程序的信息,如主消息调度代码以及顶层窗口等。
MFC在开发的时候封装了一些全局的API函数,在这些函数的前面都会加上Afx这样的标志,因为是全局的函数,所以你在App类中不会找到,返回值是获得一个CWINApp类指针,至于什么时候会用到,当你要访问CWINApp类成员时候可以用啊,还有共享的时候也可以用的。AfxGetApp();在文档中十分重要,它是一个全局函数,可以取得类的指针。在视图、框架、文档中起到穿针引线的作用,用它可以在它们之间随意的访问调用
2: CWinThread Class Members
Data Members
m_bAutoDelete | Specifies whether to destroy the object at thread termination. |
m_hThread | Handle to the current thread. |
m_nThreadID | ID of the current thread. |
m_pMainWnd(主窗口变量) | Holds a pointer to the application’s main window. |
m_pActiveWnd | Pointer to the main window of the container application when an OLE server is in-place active. |
补充:只有CWinThread对象才有m_pMainWnd
class CWinThread : public CCmdTarget
{
DECLARE_DYNAMIC(CWinThread)
public:
// Constructors
CWinThread();
BOOL CreateThread(DWORD dwCreateFlags = 0, UINT nStackSize = 0,
LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL);
// Attributes
CWnd* m_pMainWnd; // main window (usually same AfxGetApp()->m_pMainWnd)
CWnd* m_pActiveWnd; // active main window (may not be m_pMainWnd)
BOOL m_bAutoDelete; // enables 'delete this' after thread termination
..............
}
//在用户界面线程中创建非模态对话框
if (!pDlg.Create(IDD_DIALOG1, NULL))
{
AfxMessageBox("窗口创建失败!");
}
else
{
pDlg.ShowWindow(SW_SHOW);
m_pMainWnd=&pDlg;
}
在创建用户界面线程时,该句一定要加上。否则在线程不会得到释放!
InitInstance是用来执行程序每次开始时都需要进行的初始化工作的最好地方。
如果用框架窗口作为主窗口,
m_pMainWnd = new CYourMainWindow;
如果用对话框作为主窗口,
CYourDlg dlg;
m_pMainWnd = &dlg;