【多线程与AfxGetMainWnd & 窗口 与 线程 有必然联系吗? & 命名空间】
笔记内容:
转载自:http://blog.youkuaiyun.com/linyaoxin/article/details/4847529
《多线程与AfxGetMainWnd的吐血遭遇……》
事情开始有点眉目了,似乎是开始多线程以后再调用::AfxGetMainWnd()->SetWindowText就会发生崩溃,但是为啥之前VC6里死活没问题?找了半天资料没答案,最后很幸运的在某个站点看到一个全英文回答:
If AfxGetMainWnd is called from the application's primary thread, itreturns the application's main window according to the above rules. If thefunction is called from a secondary thread in the application, the functionreturns the main window associated with the thread that made the call.
在多线程里调用AfxGetMainWnd返回的是与线程有关联的主窗体?但是我这程序只有一个窗体,但是它仍然崩溃,差不多明白了,多线程里获得的句柄不等于真正的窗体句柄,对这个句柄进行“非法写操作”,于是崩溃了……
// "多线程里获得的句柄不等于真正的窗体句柄",这句话不理解?
// 有多个窗口,多个线程,此时,各个线程中调用 AfxGetMainWnd() 返回的是什么呢?
// 有一个窗口,多个线程,此时,各个线程中调用 AfxGetMainWnd() 返回的又是什么呢? Trylater。
// 窗口 与 线程 有必然联系吗?
了解了症状就好办了,在全局里写一个窗口句柄类变量
CWnd* m_pCWnd;
然后在初始化过程OnInitDialog里加上
m_pCWnd = AfxGetMainWnd();
// 这里为什么不用命名空间限定符,即 m_pCWnd = ::AfxGetMainWnd();
以后要写窗体标题的时候就用m_pCWnd->SetWindowText,将程序里所有AfxGetMainWnd改为m_pCWnd,重新编译运行,终于不再崩溃了!