我是靠谱客的博主 生动溪流,这篇文章主要介绍MFC的用户界面线程,现在分享给大家,希望可以做个参考。

一.简单认识

MFC中将线程分为用户界面线程和工作线程,两者最大的区别是前者是和界面相关联的,而后者是进行后台的一些操作.

二.如何创建

MFC中的线程大多继承自CWinThread,而相关联的界面可以继承自CFrameWnd,也可以继承自对话框之类的(感觉只要是界面类,就可以吧).

它的创建过程大概是这样的:

1.在主线程中建立用户界面线程,比如这里是CMyThread类型的.

2.在CMyThread::InitInstance中去创建一个界面对象,比如这里是CMyWnd类型的.此时就相当于把用户界面和该线程进行了关联.

3.在界面对象类中去实现你想要执行的操作,比如鼠标左键会弹出MessageBox之类的.

三.举个例子

假如你要完成这样的功能:

在主窗口中点击鼠标左键,创建用户界面线程,然后在新的界面中点击鼠标左键弹出MessageBox.

它的实现逻辑大致如下.

四.关键代码

这里是用对话框作为主窗口来实现的.

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//MyThread2.h #pragma once #include "afxwin.h" #include "MyWnd2.h" class CMyThread2 : public CWinThread { public: CMyThread2(); ~CMyThread2(); //重写父类的方法 virtual BOOL InitInstance(); virtual int ExitInstance(); public: CMyWnd2 *m_pMyWnd; };
复制代码
1
//MyThread2.cpp
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdafx.h" #include "MyThread2.h" CMyThread2::CMyThread2() { } CMyThread2::~CMyThread2() { if (m_pMyWnd) { delete m_pMyWnd; m_pMyWnd = NULL; } } BOOL CMyThread2::InitInstance() { m_pMyWnd = new CMyWnd2(); m_pMyWnd->Create(NULL, _T("用户界面线程")); m_pMyWnd->ShowWindow(SW_SHOW); m_pMyWnd->UpdateWindow(); return TRUE; //此处要返回TRUE,否则线程生成不了.why?(暂莫发散) } int CMyThread2::ExitInstance() { return 0; }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//MyWnd2.h #pragma once #include "afxwin.h" class CMyWnd2 : public CFrameWnd { public: CMyWnd2(); ~CMyWnd2(); //重写父类的方法 afx_msg void OnLButtonDown(UINT nFlags, CPoint point); DECLARE_MESSAGE_MAP()  //这里需要此声明,否则BEGIN_MESSAGE_MAP那里会报错.
复制代码
1
};
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//MyWnd2.cpp #include "stdafx.h" #include "MyWnd2.h" CMyWnd2::CMyWnd2() { } CMyWnd2::~CMyWnd2() { } BEGIN_MESSAGE_MAP(CMyWnd2, CWnd) ON_WM_LBUTTONDOWN() //如果要用到这个响应,就需要在这里声明. END_MESSAGE_MAP() void CMyWnd2::OnLButtonDown(UINT nFlags, CPoint point) { MessageBox(_T("终于等到你了"), _T("你好啊"), MB_OK); CWnd::OnLButtonDown(nFlags, point); }
复制代码
1
2
3
4
5
6
7
8
9
//UserInterfaceThreadDlg.cpp(主窗口)中的关键代码 void CUserInterfaceThreadDlg::OnLButtonDown(UINT nFlags, CPoint point) { //AfxBeginThread(RUNTIME_CLASS(CMyThread2));//使用这种方法会报内存不足的错误. CMyThread2 *myThread = new CMyThread2(); //?? 在这里new,在哪里去释放呢? myThread->CreateThread(); CWnd::OnLButtonDown(nFlags, point); //记得要把父类的方法在最后写上 }

本文参考文章:https://www.cnblogs.com/lidabo/p/3489639.html

最后

以上就是生动溪流最近收集整理的关于MFC的用户界面线程的全部内容,更多相关MFC内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部