c ++窗口没有第二次创建

时间:2017-10-29 18:52:11

标签: c++ windows windows-applications registerclass

下面的代码创建了一次窗口,但是当再次调用该函数时,它无法加载窗口。我想做到这一点,每次调用函数时我都能得到相同的效果。

int nRandWidth = 150, nRandHeight = 15, nSpeed = 1;
int nScreenWidth, nScreenHeight;

LRESULT WINAPI MelterProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch (Msg) {
    case WM_CREATE:
    {
        HDC hdcDesktop = GetDC(HWND_DESKTOP);
        HDC hdcWindow = GetDC(hWnd);
        BitBlt(hdcWindow, 0, 0, nScreenWidth, nScreenHeight, hdcDesktop, 0, 0, SRCCOPY);
        ReleaseDC(hWnd, hdcWindow);
        ReleaseDC(HWND_DESKTOP, hdcDesktop);
        SetTimer(hWnd, 0, nSpeed, NULL);
        ShowWindow(hWnd, SW_SHOW);
    }
    return 0;
    case WM_ERASEBKGND:
        return 0;
    case WM_PAINT:
        ValidateRect(hWnd, NULL);
        return 0;
    case WM_TIMER:
    {
        HDC hdcWindow = GetDC(hWnd);
        int nXPos = (rand() % nScreenWidth) - (nRandWidth / 2),
            nYPos = (rand() % nRandHeight),
            nWidth = (rand() % nRandWidth);
        BitBlt(hdcWindow, nXPos, nYPos, nWidth, nScreenHeight, hdcWindow, nXPos, 0, SRCCOPY);
        ReleaseDC(hWnd, hdcWindow);
    }
    return 0;
    case WM_CLOSE:
    case WM_DESTROY:
    {
        KillTimer(hWnd, 0);
        PostQuitMessage(0);
    }
    return 0;
    }
    return DefWindowProc(hWnd, Msg, wParam, lParam);
}

int ShiftPixels()
{
    nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
    nScreenHeight = GetSystemMetrics(SM_CYSCREEN);

    WNDCLASS wndClass = { 0, MelterProc, 0, 0, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), 0, NULL, L"Melter" };


    if (!GetClassInfo(GetModuleHandle(NULL), L"Melter", &wndClass))
    {
        if (!RegisterClass(&wndClass))
        {
            MessageBox(NULL, L"Cannot register class!", NULL, MB_ICONERROR | MB_OK);
        }
    }
    HWND hWnd = CreateWindow(L"Melter", NULL, WS_POPUP, 0, 0, nScreenWidth, nScreenHeight, HWND_DESKTOP, NULL, GetModuleHandle(NULL), NULL);
    if (!hWnd) return MessageBox(HWND_DESKTOP, L"Cannot create window!", NULL, MB_ICONERROR | MB_OK);

    srand(GetTickCount());
    MSG Msg = { 0 };
    while (Msg.message != WM_QUIT) {
        if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
        if (GetAsyncKeyState(VK_ESCAPE) & 0x8000)
            break;
    }
    DestroyWindow(hWnd);
    UnregisterClass(L"Melter", GetModuleHandle(NULL));
    return 0;
}

int main()
{
    while (true)
    {
        ShiftPixels();
        Sleep(5000);
    }
    return 0;
}

如何修改上面的代码以使其多次运行?我取消注册了Windows类并销毁了窗口。

0 个答案:

没有答案