我无法创建Window

时间:2012-10-14 10:04:20

标签: c++ windows

我试图创建窗口已经好几天了,但总是告诉我“无法创建窗口” 当它随机创建窗口时,CPU会增加50%。你能帮助我并告诉导致错误的原因吗? 这是源代码:

#include<Windows.h> 
int AppRunning=1;
void TellError(LPCWSTR error,HWND hWnd=NULL);
LRESULT CALLBACK WindowProcedure(HWND hWnd,UINT msg,WPARAM wparam,LPARAM lparam)
{
    switch(msg){
        case WM_KEYDOWN:
            AppRunning=0;
            break;
        case WM_CLOSE:
            DestroyWindow(hWnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
    }
    return DefWindowProc(hWnd,msg,wparam,lparam);
}

HWND NewWindow(LPCTSTR title,int xpos, int ypos, int width, int height)
{
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WindowProcedure;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = GetModuleHandle(NULL);
    wcex.hIcon = NULL;
    wcex.hCursor = NULL;
    wcex.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"Svet-ver1.0";
    wcex.hIconSm = LoadIcon(NULL,IDI_APPLICATION); 
    if(!RegisterClassEx(&wcex)){
        TellError(L"Cannot register window!");
        return NULL;
    }
    return CreateWindowEx(WS_EX_CONTROLPARENT, L"Svet3D-ver1.0", title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, xpos, ypos, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);
 }

 int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,LPSTR lpCmdLine,int nCmdShow)
 {
    MSG msg;
    HWND hWnd = NewWindow(L"Svet",100,100,500,500); 
    if(!hWnd){
        TellError(L"Cannot create window!");
        return 0;
    }
    while(AppRunning){
        if(PeekMessage(&msg,hWnd,0,0,PM_REMOVE)){
            if(!IsDialogMessage(hWnd,&msg)){
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
    DestroyWindow(hWnd);
    return 0;
 }
 void TellError(LPCWSTR error,HWND hWnd){
     MessageBox(hWnd,error,NULL,MB_OK);
 }

1 个答案:

答案 0 :(得分:5)

传递给RegisterClassEx的类名是"Svet-ver1.0",但在创建窗口时,您使用的是其他类名"Svet3D-ver1.0"

此外,您在主循环中使用PeekMessage,这将在队列中没有消息时快速循环。这个空循环就是燃烧所有CPU的原因(50%可能是因为你有一个双核系统)。

您应该使用GetMessage代替下一条消息,而不会浪费CPU时间。