加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

MFC实现UI线程

(2011-05-22 20:46:20)
标签:

mfc

ui

线程

it

MFC实现UI线程


本文同步发到http://codekernel.wordpress.com/。

1、        新建一个MFC的单文档应用程序,如下:

MFC实现UI线程

建立好的工程如下所示:

MFC实现UI线程

2、添加一个类MyThread,基类是:CWinThread

MyThread.h文件里添加如下代码:

DECLARE_DYNCREATE(MyThread)//声明动态生成

public:

    MyThread(void);

    ~MyThread(void);

    //{{AFX_VIRTUAL(MyThread)

public:

    virtual BOOL InitInstance();//初始化实例

    virtual int ExitInstance();//退出

    //}}AFX_VIRTUAL

    void MyMessageHandler(WPARAM, LPARAM);//线程的消息处理函数

    // Generated message map functions

    //{{AFX_MSG(MyThread)

    // NOTE - the ClassWizard will add and remove member functions here.

    //}}AFX_MSG

DECLARE_MESSAGE_MAP()//声明消息映射

 

MyThread.cpp里添加代码如下:

在文件的开头添加:(这一行比较重要)

IMPLEMENT_DYNCREATE(MyThread, CWinThread)//这里是要调用的,不然就会

 

 

什么消息映射:

//MyThread.cpp

BEGIN_MESSAGE_MAP(MyThread, CWinThread)

    //{{AFX_MSG_MAP(CMyThread)

    // NOTE - the ClassWizard will add and remove mapping macros here.

    ON_THREAD_MESSAGE ( WM_MYTHREADMESSAGE, MyMessageHandler )

    //}}AFX_MSG_MAP

END_MESSAGE_MAP()

编写消息映射函数如下:

void MyThread::MyMessageHandler(WPARAM, LPARAM)

{

    //required functionality.

    CFrameWnd *l_FrameWnd;

    CView *l_View;

    l_FrameWnd = (CFrameWnd *)AfxGetApp()->m_pMainWnd;

    l_View = l_FrameWnd ->GetActiveView();

    CClientDC dc(l_View);

    dc.TextOut(100,y,TEXT("Hello"));

    y = y+30;

}

 

下面这两个函数几乎可以不用实现

InitInstance()

ExitInstance(){return CWinThread::ExitInstance();}

 

2、        在工程的view类里添加生成线程的代码

MyThread* pThread;

      pThread = new MyThread();

      pThread->CreateThread();

      pThread->PostThreadMessage(WM_MYTHREADMESSAGE,NULL,NULL);

这里发送消息了之后,就会在view里看见一行字,实现这个功能的代码在线程里。

运行结果如下:

MFC实现UI线程

后记:MFC里可以有两种线程,一种是工作线程,一种是界面线程。

工作线程是运行完就退出,UI线程将一直存在直到程序最后结束。

UI线程可以有自己的消息队列,但是工作线程是不可以有的。

不过有一个疑问,一个UI线程可以有多个消息队列吗?

 

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有