c++ Window doesn't get created second time

109 Views Asked by At

The code below creates the windows once, but when the function is called again, it fails to load the window. I want to make it so that I can get the same effect every time I call the function.

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;
}

How can I modify the code above to make it run multiple times ? I've Unregistered the windows class and destroyed the windows.

0

There are 0 best solutions below