注册 登录
编程论坛 C++教室

初学win 32 窗体创建hwnd 遇到创建hwnd为空 请问什么原因

zxlovezxl 发布于 2017-03-24 23:16, 2588 次点击
以下是 全部代码,建Win32 空项目,c.bmp文件一个
#include <windows.h>
#include <iostream>
#include <time.h>
using namespace std;
const string APPTITLE = "Game Loop";
HWND window;
HDC device;
bool gameover = false;
void DrawBitmap(char *filename, int x, int y)
{
    HBITMAP image = (HBITMAP)LoadImage(0, "c.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    BITMAP bm;
    GetObject(image, sizeof(BITMAP), &bm);
    HDC hdcImage = CreateCompatibleDC(device);
    SelectObject(hdcImage, image);
    BitBlt(device, x, y, bm.bmWidth, bm.bmHeight, hdcImage, 0, 0, SRCCOPY);
    DeleteDC(hdcImage);
    DeleteObject((HBITMAP)image);
}
bool Game_Init()
{
    srand(time(NULL));
    return 1;
}
void Game_Run()
{
    if (gameover == true) return;
    RECT rect;
    GetClientRect(window, &rect);
    int x = rand() % (rect.right - rect.left);
    int y = rand() % (rect.bottom - rect.top);
    DrawBitmap("c.bmp", x, y);
}
void Game_End()
{
    ReleaseDC(window, device);
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        gameover = true;
        PostQuitMessage(0);
        break;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.lpfnWndProc = (WNDPROC)WinProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = APPTITLE.c_str();
    wc.hIconSm = NULL;
    return RegisterClassEx(&wc);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    window = CreateWindow(APPTITLE.c_str(), APPTITLE.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);
    if (window == 0) return 0;
    ShowWindow(window, nCmdShow);
    UpdateWindow(window);
    device = GetDC(window);
    return 1;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg;
    MyRegisterClass(hInstance);
    if (!InitInstance(hInstance, nCmdShow)) return 0;
    if (!Game_Init()) return 0;
    while (!gameover)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        Game_Run();
    }
    Game_End();

    return msg.wParam;
}
请问为什么 不出结果,一闪而过,window为什么为空
5 回复
#2
yangfrancis2017-03-25 12:16
Win32程序不建立InitInstance, 是在MainWin内CreateWindow,回调函数中处理WM_CREATE
#3
yangfrancis2017-03-25 12:17
说错了,是WinMain
#4
rjsp2017-03-27 08:38
你应该告诉别人 MyRegisterClass(hInstance); 执行失败

原因是 wc.style 未赋值。
#5
zxlovezxl2017-03-27 11:55
高手啊一语道破 谢谢,已解决
#6
yangfrancis2017-03-27 13:57
确实没仔细看
1