wxWidgets从控制台窗口创建GUI窗口

wxWidgets提供了两种程序类型:控制台程序和GUI程序。有时为了方便调试或其它目的需要控制台窗口,或者从控制台创建窗口。GUI窗口创建控制台窗口可以通过AllocConsole API函数实现,本文给出从控制台创建GUI窗口的方法。

一、原理

采用win32 API从控制台创建GUI窗口可以通过如下方式实现:

include <windows.h>

int main(int argc,char* argv[])
{
    //获取实例句柄
    HINSTANCE hInstance = GetModuleHandle(NULL);

    //和WIN32 GUI程序中的winmain类似:
    //1)注册窗体类
    //2)消息循环

    return 0;
}

对于wxWidgets而言,只要找到对应的winmain,将其中内容拷贝到上述main中即可。如何找到winmain?只有在wxWidgets中查找了。

二、实现

通过对宏IMPLEMENT_APP展开,顺藤摸瓜的方式可以发现winmain定义在宏IMPLEMENT_WXWIN_MAIN中:

#define IMPLEMENT_WXWIN_MAIN \
    extern "C" int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,wxCmdLineArgType lpCmdLine,int nCmdShow) \
    {return wxEntry(hInstance, hPrevInstance, lpCmdLine, nCmdShow);} \
    IMPLEMENT_WXWIN_MAIN_BORLAND_NONSTANDARD
 
因此只需将“wxEntry(hInstance, hPrevInstance, lpCmdLine, nCmdShow);”拷贝到main中即可。完整的代码如下:
 
#include <stdio.h>
#include <wx/app.h>
#include <wx/frame.h>

// -------------------------------------------------------------------
// Declare MyApp
// -------------------------------------------------------------------
class MyApp : public wxApp
{
public:
    MyApp();

    virtual bool OnInit();
    virtual int OnExit();

private:
    DECLARE_NO_COPY_CLASS(MyApp)
};
DECLARE_APP(MyApp)

// -------------------------------------------------------------------
// Impliment MyApp
// -------------------------------------------------------------------
IMPLEMENT_APP_NO_MAIN(MyApp) // <-- 默认为IMPLEMENT_APP(MyApp)
IMPLEMENT_WX_THEME_SUPPORT

MyApp::MyApp()
{
}

bool MyApp::OnInit()
{
    // create frame
    wxFrame *frame = new wxFrame(0,wxID_ANY,wxT("Chart"));
    frame->Show();
    
    return true;
}

int MyApp::OnExit()
{
    return 0;
}

// application entry
int main(int argc, char* argv[])
{
    // get HINSTANCE of current application
    HINSTANCE hInstance = GetModuleHandle(NULL),hPrevInstance = NULL;
    // get command line
    wxCmdLineArgType lpCmdLine = GetCommandLine();

    // create GUI window
    return wxEntry(hInstance, NULL, lpCmdLine, SW_SHOW);
}

程序在wxWidgets-2.8.10 + VS2005下调试通过

posted on 2010-02-22 14:36  codezhang  阅读(1650)  评论(0编辑  收藏  举报

导航