c++windowswinapibutton

Strange Behavior of EnableWindow on Button


I have a simple Win32 application that creates a button. Right after the button is created i disabled it using the EnableWindow(FALSE) function from the <windows.h>. It works normal when the button size is greater than the text applied. But when the button size is smaller that the text of the button the client area of the entire window seems to copy the contents of the screen.

The size is greater that the text (Normal)

The size is smaller that the text (Problem)

Code that causes the bug:

#include <Windows.h>

LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR    lpCmdLine, _In_ int       nCmdShow)
{
    WNDCLASSEX wcex = { 0 };

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.lpfnWndProc = WndProc;
    wcex.hInstance = hInstance;
    wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wcex.lpszClassName = L"MYWINDOWCLASS";
    
    if (RegisterClassExW(&wcex) == 0)
        return -1;

    HWND hWnd = CreateWindowW(L"MYWINDOWCLASS", L"MYWINDOW", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

    if (!hWnd)
        return -1;

    HWND buttonHWnd = CreateWindowW(L"BUTTON", L"MYWINDOW", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        100, 100, 40, 30, hWnd, nullptr, hInstance, nullptr);

    if (!buttonHWnd)
        return -1;

    EnableWindow(buttonHWnd, FALSE);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    MSG msg;
    while (GetMessage(&msg, nullptr, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}


Solution

  • As @RemyLebeau said, @OldBoy 's comment should be posted as an answer. Promote @OldBoy 's comment to answer.

    Your code is incomplete for two reasons: 1. You have not declared a background brush in your WNDCLASSEX structure, so you may not get the background you expect. 2. You do not have a handler for WM_PAINT messages, so whatever shows on the background of the window is not guaranteed.