关于调用AfxGetMainWnd()的问题

小小爬虾 2013-04-13 06:02:19
今天看到有文章说:如果不是在主线程中调用AfxGetMainWnd(),那么就得不到程序的主窗口,于是,我创建了一个工作者子线程,在子线程中调用AfxGetMainWnd(),却仍能得到主窗口的句柄,这是为何呢?
代码如下(基于对话框的MFC EXE VC6.0,有一个按钮和一个文本框,按钮用来创建子线程,文本框用来显示主窗口的句柄值)

UINT ThreadProc(LPVOID pParam)
{
CWnd* pDlg=AfxGetMainWnd();//得到主窗口的指针
HWND hwnd=pDlg->m_hWnd;//得到主窗口的句柄
::SetDlgItemInt(hwnd,IDC_EDIT1,(int)hwnd,FALSE);//用文本框显示主窗口句柄
return 0;
}
void CAfxGetMainWndDlg::OnButton1()
{
CWinThread* pThread=AfxBeginThread(ThreadProc,NULL);//创建子线程
}
...全文
159 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
heqiangfly 2013-04-14
  • 打赏
  • 举报
回复
引用 3 楼 kxltsuperr 的回复:
引用 1 楼 heqiangfly 的回复:文章里说的应该是指新建线程是从CWinThread派生出来的线程类,不是你现在用的这种纯函数式的 还是不太明白...
AfxBeginThread有两种形式,你给的例子是第一种,我没有这么用过,我一般是直接传指针。第二种形式前段时间正好用过,不幸的是在新生成的线程中调用了AfxGetMainWnd(),失败,后来还是改为传指针解决。 总之,AfxBeginThread第二种形式生成的用户界面线程不能通过调用AfxGetMainWnd()获得主线程的主窗口指针。 CWinThread* AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); The first form of AfxBeginThread creates a worker thread. The second form creates a user-interface thread.
Eleven 2013-04-13
  • 打赏
  • 举报
回复
AfxBeginThread创建线程的时候,直接上主窗口的HWND窗口句柄作为线程函数的参数传递给线程即可。
小小爬虾 2013-04-13
  • 打赏
  • 举报
回复
引用 1 楼 heqiangfly 的回复:
文章里说的应该是指新建线程是从CWinThread派生出来的线程类,不是你现在用的这种纯函数式的
还是不太明白...
Jake443403168 2013-04-13
  • 打赏
  • 举报
回复
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.
heqiangfly 2013-04-13
  • 打赏
  • 举报
回复
文章里说的应该是指新建线程是从CWinThread派生出来的线程类,不是你现在用的这种纯函数式的

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧