我的C++窗口程序运行,但我看不到



下面是代码。运行时,不显示窗口,也没有错误消息。我做错了什么?

//WinApp.h
#pragma once
#include<Windows.h>
class WinApp
{
private: HWND hWnd;
         MSG msg;
         static WinApp *instance;
public: 
    WinApp(void);
    ~WinApp(void);
    void CreateWnd(HINSTANCE hInstance, int iCmdShow);
    int Run(HINSTANCE hInstance, int iCmdShow);
    void Release();
    static HRESULT CALLBACK WndProc(HWND hwnd, UINT imsg, WPARAM wParam, LPARAM lParam);// window proc
    static WinApp* GetInstance();
};
//WinApp.cpp
#include "WinApp.h"
#include<Windows.h>
WinApp::WinApp(void)
{
    hWnd=NULL;
    ZeroMemory(&msg,sizeof(MSG));
}
WinApp::~WinApp(void)
{
    delete hWnd;
}
void WinApp::CreateWnd(HINSTANCE hInstance, int iCmdShow){
    WNDCLASSEX WndClassex;
    ZeroMemory(&WndClassex, sizeof(WNDCLASSEX));
    WndClassex.cbSize=sizeof(WNDCLASSEX);
    WndClassex.hCursor=LoadCursor(NULL, IDC_ARROW);
    WndClassex.hIcon=LoadIcon(NULL, IDI_APPLICATION);
    WndClassex.hbrBackground=(HBRUSH) GetStockObject(WHITE_BRUSH);
    WndClassex.hInstance=hInstance;
    WndClassex.style=CS_HREDRAW|CS_VREDRAW;
    WndClassex.lpszClassName=L" ";
    WndClassex.lpszMenuName=NULL;
    WndClassex.lpfnWndProc=&WinApp::WndProc;
    RegisterClassEx(&WndClassex);
    hWnd=CreateWindowEx(0,
        L" ",
        L"UNUSUAL",
        WS_CAPTION|WS_MINIMIZEBOX|WS_SYSMENU|WS_THICKFRAME,
        0, 
        0,
        512,
        512,
        NULL,
        NULL,
        hInstance,
        NULL
        );
    ShowWindow(hWnd, SW_RESTORE);
    UpdateWindow(hWnd);
}
void WinApp::Release(){
    delete this;
}
int WinApp::Run(HINSTANCE hInstance, int iCmdShow){
    this->CreateWnd(hInstance, iCmdShow);
    while(GetMessage(&msg, NULL, 0, 0)){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return (int)msg.wParam;
}
WinApp* WinApp::instance=0;
WinApp* WinApp::GetInstance(){
    if(instance==NULL){
        instance=new WinApp;
    }
    return instance;
}
HRESULT WinApp::WndProc(HWND hwnd, UINT imsg,WPARAM wParam, LPARAM lParam ){
    switch (imsg)
    {
    case WM_PAINT:
        HDC hdc;
    PAINTSTRUCT ps;
    RECT rect;
            hdc = BeginPaint (hwnd, &ps);
            GetClientRect (hwnd, &rect);
            FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
            EndPaint (hwnd, &ps);
            break;
    case WM_QUIT:
        PostQuitMessage(0);
        WinApp::GetInstance()->Release();
        break;
    default: DefWindowProc(hwnd, imsg, wParam, lParam);
        break;
    }
    return 0;
}
//main.cpp
#include<Windows.h>
#include"WinApp.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpszCmdLine, int iCmdShow){
    WinApp::GetInstance()->Run(hInstance, iCmdShow);
    return 0;
}

你的代码有很多问题。

但除此之外,你的窗口没有显示的原因是WinApp::WndProc没有返回DefWindowProc的结果。

所以只需改变

default:
    DefWindowProc(hwnd, imsg, wParam, lParam);
    break;

default:
    return DefWindowProc(hwnd, imsg, wParam, lParam);

相关内容

最新更新