创建单独的 MFC GUI 线程,不能 move/resize/maximize CWnd

Creating separate MFC GUI thread, can't move/resize/maximize CWnd

我正在创建一个 CWinThread,它将拥有自己的 GUI。当我在该线程上创建 CWnd 时,它会显示,但我无法移动 window。我确定消息泵是 运行,因为我可以从另一个线程执行 MoveWindow,并且 window 移动。

UIThread.h

#pragma once

class CUIThread : public CWinThread
{
public:
    DECLARE_DYNCREATE(CUIThread)
    CUIThread();

    // Attributes
public:
    HWND hwnd;
    // Operations
public:
    void KillThread();

    // Overrides
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CGDIThread)
    //}}AFX_VIRTUAL

    // Implementation
public:
    virtual ~CUIThread();

protected:
    virtual BOOL InitInstance();

    // Generated message map functions
    //{{AFX_MSG(CUIThread)
    // NOTE - the ClassWizard will add and remove member functions here.
    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()
};

UIThread.cpp

#include "stdafx.h"
#include "UIThread.h"

#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CUIThread

IMPLEMENT_DYNCREATE(CUIThread, CWinThread)

BEGIN_MESSAGE_MAP(CUIThread, CWinThread)
    //{{AFX_MSG_MAP(CUIThread)
    // NOTE - the ClassWizard will add and remove mapping macros here.
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

CUIThread::CUIThread() : hwnd(NULL)
{
    m_bAutoDelete = FALSE;
}

BOOL CUIThread::InitInstance()
{
    this->m_pMainWnd = new CWnd;
    m_pMainWnd->Create(_T("STATIC"), _T("Hi"), WS_VISIBLE | WS_OVERLAPPEDWINDOW,
        CRect(0, 0, 500, 500), CWnd::GetDesktopWindow(), 1234);

    this->hwnd = m_pMainWnd->GetSafeHwnd();

    return TRUE;
}

CUIThread::~CUIThread()
{

}

void CUIThread::KillThread()
{
    // Note: this function is called in the context of 
    // other threads, not the thread itself.
    this->PostThreadMessage(WM_QUIT, 0, 0);

    // allow thread to run at higher priority during 
    // kill process
    SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
    WaitForSingleObject(m_hThread, INFINITE);
}

main.cpp

...
CUIThread* pUIThread = static_cast< CUIThread*>(AfxBeginThread(RUNTIME_CLASS(CUIThread)));
getchar();
MoveWindow(pUIThread->hwnd, 100, 100, 500, 500, true); // works
getchar();
CloseWindow(pUIThread->hwnd); // works
getchar();
pUIThread->KillThread(); // works
delete pUIThread;
getchar();
...

我能看到 window,我就是看不到 move/maximize/resize。

我认为您创建 window 的方式有误。您正在创建一个子 window 并将桌面作为父 window。这应该有效:

LPCSTR strClass = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE);
VERIFY(m_pMainWnd->CreateEx(0, strClass, _T("title"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CRect(0, 0, 500, 500), NULL, 0));