我自己的 C++ 框架(类似 MFC),我可以创建子窗口,但在 WM_CREATE 时无法创建编辑框

Posted

技术标签:

【中文标题】我自己的 C++ 框架(类似 MFC),我可以创建子窗口,但在 WM_CREATE 时无法创建编辑框【英文标题】:My Own C++Framework (MFC-like), i can create child window, but cant create edit box when WM_CREATE 【发布时间】:2012-08-28 18:33:51 【问题描述】:

我构建了自己的与 MFC 类似的 c++ 框架,我可以在收到 WM_CREATE 消息时创建子窗口,但我无法处理编辑框,我从Ivan Shcherbakov's post 得到了这个想法,我发布了一个 WM_CREATEMYWINDOW调用 OnCreate 后的消息,并在收到消息时在 OnCreateMyWindow 函数中创建一些东西,当然,它可以工作。但我想知道为什么以及如何解决这个问题。

我的 CWnd 是 CMyWindow,我创建了一个 CBT-hook 来保存新窗口的 HWND 和 CMyWindow*,然后作为 WindowManager 添加到 HWND-WINDOW 映射,消息循环回调函数 MyWndProc,从 WindowManger 获取 CMyWindow* hWnd 参数,然后调用 CMyWindow 的消息函数 OnCreate、OnSize、OnMove ...等,就像 CWnd 类一样。

CMyWindow 看起来很好用,它可以保存所有消息并做一些响应,但是它不能在 WM_CREATE 时创建一个编辑框,它是如此的连线,因为它在 WM_CREATE 时创建了一个具有任何样式的新窗口。

我用vs2010,win7构建的。

MyWindow.h 中的 WindowManager(HWND-WINDOW 映射)

#define WM_CREATEMYWINDOW WM_USER + 123

//the CWindowManager is a map of HWND-CMyWindow
class CMyWindow;
//define the HWND-CMyWindow map
typedef map <HWND, CMyWindow*> CWindowMap;
typedef pair<HWND, CMyWindow*> WindowPair;
typedef map <HWND, CMyWindow*>::iterator WndIterator;
typedef pair<WndIterator, bool> IterBool;

class CWindowManager : private CWindowMap

private:
    CWindowManager(void);
    ~CWindowManager(void);
public:
    bool Add(CMyWindow* pwnd);  //add a window to map
    bool Remove(HWND hwnd);     //remove a window by hwnd
    void Clear();               //remove all items
    CMyWindow* Find(HWND hwnd); //find the window by hwnd

public:
    //get CWindowManager instance as singleton pattern
    static CWindowManager * GetInstance();
;

CMyWindow 类与 MFC 的 CWnd 类似

class CMyWindow

public:
    CMyWindow(void);
    ~CMyWindow(void);

    inline HWND GetSafeHwnd();  //get HWND
    //Create a window
    bool Create( HINSTANCE hInstance,
                TCHAR * szWindowName,
                       DWORD dwStyle,
                          RECT& rect,
                     HWND hParentWnd,
                         HMENU hMenu,
                     LPVOID lpParam);
    //add the window to WindowManager
    void Attach(HWND hwnd);
    //remove the window from WindowManager
    void Dettach();

    //process the WM_CREATE message
    virtual int OnCreate(LPCREATESTRUCT ps);
    /*
        other message function
    */
    //process the WM_CREATEMYWINDOW message
    virtual void OnCreateMyWindow();
protected:
    HWND _hwnd;
    HINSTANCE _hInst;
;

MyWindow.cpp 中的 WindowManager 和 CBT-HOOK 部分

#include "StdAfx.h"
#include "LockEx.h"
#include "MyWindow.h"

//window class name
static TCHAR * _MY_WINDOW_CLASS_NAME_ = L"MYWINDOWCLASS";

//window-proc
LRESULT CALLBACK MyWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

///an Mutex-Lock class for keep current hwnd of new window, but you can ignore it when using single thread to crate window
static CLockEx   gLockInitWnd;
///keep current hwnd of new window
static CMyWindow * gpInitWnd = 0;
///an hook to create new window
static HHOOK ghook = 0;


///set gpInitWnd when create a new window
static void SetInitWnd(CMyWindow * pWnd)

    CLockEx::Scoped lock(gLockInitWnd);

    gpInitWnd = pWnd;


///clear gpInitWnd after new window created
static void UnsetInitWnd()

    CLockEx::Scoped lock(gLockInitWnd);

    gpInitWnd = 0;


///get the HWND of new window that is creating
static CMyWindow * GetInitPwnd()

    CLockEx::Scoped lock(gLockInitWnd);

    return gpInitWnd;


//CBT-Proc for SetWindowsHookEx
static LRESULT CALLBACK MyCBTProc(int nCode, WPARAM wParam, LPARAM lParam)

    if (nCode == HCBT_CREATEWND) 
        //get the new window from gpInitWnd
        CMyWindow * pwnd = GetInitPwnd();

        if (pwnd) 
            //first time call this proc
            //add this window to WindowManager
            pwnd->Attach((HWND)wParam);
            return (0);
         else 
            //sencond time call this proc
            CREATESTRUCT * cs = ((CBT_CREATEWND *)lParam)->lpcs;
            if (!(cs->style & WS_CHILD)) 
                //we can do something here
                return (0);
             else 
                return (1); //error, destroy the window
                            //or, maybe, CallNextHookEx
            
        
     else
        return CallNextHookEx(ghook, nCode, wParam, lParam);


//Create a WH_CBT Hook
static bool HookCrate()

   HANDLE hThread = GetCurrentThread();
   DWORD dwThreadId = GetThreadId(hThread);
   if (hThread) 
        ghook = SetWindowsHookEx(
            WH_CBT,
            MyCBTProc,    //set the CBT proc
            0,
            dwThreadId);
        if (!ghook)
            return false;
   

   return (0);


//Destroy WH_CBT Hook
static void HookDestroy()

   if (ghook) 
        UnhookWindowsHookEx(ghook);
        ghook = 0;
   


///////////////////////////////////////////////
//this is a vector for keep all CMyWindow*
CWindowManager::CWindowManager(void)



CWindowManager::~CWindowManager(void)

    clear();


//insert new window
bool CWindowManager::Add(CMyWindow* pwnd)

    IterBool ib = insert(WindowPair(pwnd->GetSafeHwnd(), pwnd));
    return ib.second;


//remove a window by hwnd
bool CWindowManager::Remove(HWND hwnd)

    WndIterator wi = find(hwnd);

    if (wi == end( )) 
        return false;
     else 
        erase(wi);
        return true;
    


//find a window by hwnd
CMyWindow* CWindowManager::Find(HWND hwnd)

    WndIterator wi = find(hwnd);

    if (wi == end( )) 
        return (0);
     else 
        return wi->second;
    


//remove all items
void CWindowManager::Clear()

    clear();


//get instance as singleton pattern.
CWindowManager * CWindowManager::GetInstance()

    static CWindowManager wm;
    return &wm;

注册窗口类,设置WndProc为MyWIndowProc

ATOM RegisteWindowClass(HINSTANCE hInstance, TCHAR * szClassName)

    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style      = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = MyWindowProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = 0;
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName   = 0;
    wcex.lpszClassName  = szClassName;
    wcex.hIconSm        = 0;    
    return RegisterClassEx(&wcex);

CMyWindow 类,请注意我在 WM_CREATE 和 WM_CREATEMYWINDOW 消息中的麻烦

CMyWindow::CMyWindow(void)
    : _hwnd(0)
    , _hInst(0)




CMyWindow::~CMyWindow(void)



inline HWND CMyWindow::GetSafeHwnd()

    return _hwnd;


//Craete a window
bool CMyWindow::Create( HINSTANCE hInstance,
                        TCHAR * szWindowName,
                        DWORD dwStyle,
                        RECT& rect,
                        HWND hParentWnd,
                        HMENU hMenu,
                        LPVOID lpParam)

    //get safe instance
    HINSTANCE hInst = hInstance;
    if (!hInstance)
        if (!hParentWnd)
            return false;
        else
            hInst = (HINSTANCE) GetWindowLong(hParentWnd, GWL_HINSTANCE);
    if (!hInst)
        return false;

    //register window class
    if (!RegisteWindowClass(hInst, _MY_WINDOW_CLASS_NAME_)) 
        DWORD dwErr = GetLastError();
        if (dwErr != ERROR_CLASS_ALREADY_EXISTS) //0x00000582
            return false;
    

    //claim i am creating 
    SetInitWnd(this);
    //create CBT hook, then this window will add to WindowManager
    HookCrate();
    //create window
    HWND hwnd = CreateWindow(
                    _MY_WINDOW_CLASS_NAME_,
                    szWindowName,
                    dwStyle,
                    rect.left, rect.right, rect.right - rect.left, rect.bottom - rect.top,
                    hParentWnd,
                    hMenu,
                    hInstance,
                    lpParam);
    //destroy CBT hook
    HookDestroy();

    if (!hwnd)
        return false;

    _hwnd = hwnd;
    _hInst = hInst;

    //show window
    ShowWindow(_hwnd, SW_SHOW);
    UpdateWindow(_hwnd);
    return true;    


//add the this window to WindowManager
void CMyWindow::Attach(HWND hwnd)

    _hwnd = hwnd;
    CWindowManager::GetInstance()->Add(this);

    UnsetInitWnd();


//remove the this window to WindowManager
void CMyWindow::Dettach()

    CWindowManager::GetInstance()->Remove(_hwnd);
    _hwnd = 0;




int CMyWindow::OnCreate(LPCREATESTRUCT ps)

    return (0);


void CMyWindow::OnCreateMyWindow()



//the WndProc callback function
LRESULT CALLBACK MyWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)

    //Get the CMyWindow instance from WindowManager by hWnd
    CMyWindow * pwnd = CWindowManager::GetInstance()->Find(hWnd);
    //can not find thi window in WindowManager
    if (!pwnd) return DefWindowProc(hWnd, message, wParam, lParam);

    switch (message)
    
    case WM_CREATE:
        
            //perform the OnCreate function, just like MFC's OnCreate
            int r = pwnd->OnCreate(reinterpret_cast<LPCREATESTRUCT>(lParam));
            if (r)  //some error occurred, will destory the window
                return (r);
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //I can not create any edit box in OnCreate function,
            //I must do it leater, when the window was created and
            //WM_CREATEMYWINDOW was received
            ::PostMessage(hWnd, WM_CREATEMYWINDOW, 0, 0);
        
        break;
    /*
    case WM_.....
        other message
    case WM_.....
    */
    case WM_DESTROY:
        ::PostQuitMessage(0);
        break;
    case WM_CREATEMYWINDOW:
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //I can not create any edit box in OnCreate function,
        //I must do it when WM_CREATEMYWINDOW was received
        pwnd->OnCreateMyWindow();
        break;
    

    return DefWindowProc(hWnd, message, wParam, lParam);

现在,继承 CMyWindow 类来创建 2 个窗口,第一个窗口将创建第二个带有编辑框的窗口

class CMyWnd2 : public CMyWindow

public:
    CMyWnd2(void) : _hCmdEdit(0) 
    ~CMyWnd2(void)

protected:
    HWND _hCmdEdit;

    //create edit box
    virtual void OnCreateMyWindow();
;


class CMyWnd1 : public CMyWindow

public:
    CMyWnd1(void) 
    ~CMyWnd1(void)

protected:
    virtual int OnCreate(LPCREATESTRUCT ps);

    //create window2
    virtual void OnCreateMyWindow();

    CMyWnd2 _wnd2;
;

int CMyWnd1::OnCreate(LPCREATESTRUCT /*ps*/)

    //Can create window2, but can not crate window2's edit-boxs
    return (0);


//create window2 with edit box
void CMyWnd1::OnCreateMyWindow()

    RECT rect = 0, 0, 400, 300;

    _wnd2.Create(this->_hInst,
        0,
        WS_VISIBLE | WS_POPUP,
        rect,
        _hwnd,
        0,
        0);



//create edit box
void CMyWnd2::OnCreateMyWindow()

    RECT rect;
    GetClientRect(_hwnd, &rect);
    _hCmdEdit = CreateWindowEx(
                            WS_EX_STATICEDGE,
                            L"EDIT",
                            NULL,
                            WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL, 
                            0,
                            rect.bottom - 80,
                            rect.right - rect.left,
                            80,
                            _hwnd,
                            (HMENU) 100,
                            (HINSTANCE) GetWindowLong(_hwnd, GWL_HINSTANCE),
                            NULL);

最后,WinMain函数创建一个CMyWnd1实例

CMyWnd1 mainwnd;
RECT rect;
rect.left = rect.top = 0, rect.right = 500, rect.bottom = 400;
mainwnd.Create(hInstance,
    L"MyWindow",
    WS_OVERLAPPEDWINDOW,
    rect,
    0,
    0,
    0);

while (GetMessage(&msg, NULL, 0, 0))

    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    

这里一定有我遗漏的东西,谁能帮我解决这个问题?

【问题讨论】:

【参考方案1】:

请注意WM_CREATE 消息在CreateWindow() 返回之前发送。这意味着窗口句柄成员_hwnd(注意:不应使用以_和__开头的标识符,它们是为编译器扩展保留的)尚未初始化并且包含0。因此后续CreateWindow()调用失败,因为您必须传递有效的窗口创建子窗口的句柄(具有WS_CHILD 样式)。但它允许用于弹出窗口(@98​​7654326@ 风格)。这很可能是创建 Wnd2 而不是编辑框的原因。

【讨论】:

嗨 Rost,感谢您的帮助!但是,1。我认为 _hwnd 是有效的句柄,否则不应创建 Wnd2,也应使用 WS_CHILD 创建 Wnd2,您可以尝试一下。 2。我尝试在没有任何 cpp 类的情况下使用原始 win32api 的“标准”进程做同样的事情,它工作得很好。那是第一个窗口在 WM_CREATE 中创建了第二个窗口,第二个窗口在他的 WM_CREATE 中创建了一个编辑框。再次感谢您! 1.您可以通过在WM_CREATE 处理程序中安装断点来检查它。根据您的代码,它应为零。 2. 当然它可以使用 API 代码——因为窗口句柄在WM_CREATE 调用中直接可用——它作为窗口过程参数传递。但不在您的 cpp 代码中... 嗨 Rost,我在 CBT-Hook 回调函数 MyCBTProc 中遇到了错误,当函数调用第二次时,我拒绝了 WS_CHILD 样式的窗口的创建请求。现在,我只是返回了一个零,一切正常! 顺便说一下,WM_CREATE 之前的 _hwnd 必须非零,因为 CBT-Hook 已捕获它并将其放入地图(hwnd-window)。再次感谢您!【参考方案2】:

我知道了,CBThook回调函数出现了一个愚蠢的错误,当第二次调用这个函数时,我拒绝了创建WS_CHILD风格窗口的请求。它只需要返回一个零!请查看 cmets 中的错误。现在它起作用了!谢谢Rost's 提示。

static LRESULT CALLBACK MyCBTProc(int nCode, WPARAM wParam, LPARAM lParam)

    if (nCode == HCBT_CREATEWND) 
        //get the new window from gpInitWnd
        CMyWindow * pwnd = GetInitPwnd();

        if (pwnd) 
            //first time call this proc
            //add this window to WindowManager
            pwnd->Attach((HWND)wParam);
            return (0);
         else 
            //sencond time call this proc
            return (0);

            ////
            /// below was my stupid code, 
            ////

            /*CREATESTRUCT * cs = ((CBT_CREATEWND *)lParam)->lpcs;
            if (!(cs->style & WS_CHILD)) 
                //we can do something here
                return (0);
             else 
                return (1); //error, destroy the window
                            //or, maybe, CallNextHookEx
            */
        
     else
        return CallNextHookEx(ghook, nCode, wParam, lParam);

【讨论】:

以上是关于我自己的 C++ 框架(类似 MFC),我可以创建子窗口,但在 WM_CREATE 时无法创建编辑框的主要内容,如果未能解决你的问题,请参考以下文章

MFC程序使用GTest搭建测试框架

C++ MFC SDI 创建子窗口

如何将 MFC 支持添加到现有的 Win32 C++ 项目?

是否像在 MFC 中那样在 nana c++ 中的画布上涂鸦的图形支持?

在 MFC C++ 中打开对话框

Qt和C++关系