我现在要生成一个线程可以收发消息,应该是一个UI线程把。我先从CWinThread中派生一个自己的类CMyThread,然后CWinThread *pt=AfxBeginThread(RUNTIME_CLASS(CMyThread));
然后应该怎么做呢?是不是应该在CMyThread的Initinstance里面在生成一个CWND对象呢?这样
我才有一个处理消息的窗口函数哦。但是如何注册窗口类呢?我只是
要一个消息循环,并不想要这个窗口现实出来。另外,我看到还有一个PostThreadMessage函数,使用这个函数要不要
生成一个CWND类?那位有UI线程的一个例子,只要实现消息循环就可以了,不要太多的其他东西。
谢谢!!

解决方案 »

  1.   

    hehe,我就是不知道怎么做,不知道能不能贴上几句关键的代码来,多谢!
      

  2.   


    class CGUIThread:public CWinThread
    {
    public:
    CGUIThread();
    virtual BOOL InitInstance(void);
    virtual int ExitInstance(void);
    };
    CGUIThread::CGUIThread()
    {
    //设置自动删除
    m_bAutoDelete = TRUE;
    }
    BOOL CGUIThread::InitInstance(void)
    {
    CWnd* pWnd=new CWnd();
    pWnd->CreateEx(0,
    AfxRegisterWndClass( CS_HREDRAW|CS_VREDRAW) ,
    "gui thread window",
    WS_OVERLAPPEDWINDOW|WS_VISIBLE,
    CRect(0,0,100,100),
    NULL,
    0);
    m_pMainWnd=pWnd;
    m_pMainWnd->ShowWindow(SW_HIDE);
    return (m_pMainWnd!=FALSE);
    }
    int CGUIThread::ExitInstance(void)
    {
    TRACE("gui thread exit\n"); return CWinThread::ExitInstance();
    }
      

  3.   

    在线程里面,写如下代码:
    while(true)
    {
      tmsg msg;
      if( PeekMessage(&msg,...) )
      {
        if(msg.message == 你的消息)
        {
           你的代码
        }
      }}在线程外面:
    PostThreadMessage(this->hwnd, 你的消息, 0, 0);大概就是这样,语法可能有些问题.我VC不是很熟悉!
      

  4.   

    可以这样启动GUI thread:
    void CSam_sp_43Dlg::OnGuiT() 
    {
    CGUIThread *p_thread1=new CGUIThread;
    p_thread1->CreateThread();
    //使用默认参数,由于CGUIThread自动删除,所以不需要保存该指针
    }
      

  5.   

    to jsphuang:这样写的话,如果另外一个线程要向这个线程发一个消息,应该怎么写?是用PostMessage发到相应的窗口吧,能不能用PostThreadmessage?to yinxu:
    这样的话,是不是不用生成窗口类了?
      

  6.   

    PostThreadMessageThe thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation: Call PostThreadMessage. If it fails, call theSleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds. 
    Create an event object, then create the thread. Use theWaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) to force the system to create the message queue. Set the event, to indicate that the thread is ready to receive posted messages. 
    The thread to which the message is posted retrieves the message by calling the GetMessage or PeekMessage function. The hwnd member of the returned MSG structure is NULL. 
      

  7.   

    CWinThread *pt=AfxBeginThread(RUNTIME_CLASS(CMyThread));
    然后PostThreadMessage就可以发消息了,其他的,可以不用,在线程里的pretranslateMsg里可以拦截处理消息。
      

  8.   

    晕!
    jsphuang(浪人)已经解决了你的问题。根据它的代码创建的线程已经具备了处理消息的功能。