Windows API - Button Control

The Button control is a standard Windows element used to initiate an action when clicked.

Introduction

Buttons are fundamental UI elements that provide users with a straightforward way to trigger commands or actions within an application. They can represent simple actions like "OK" or "Cancel", or more complex operations.

Types of Buttons

Common Styles and Attributes

Button controls can be customized using various styles:

Key Messages

Applications interact with button controls by sending messages. The most common message is:

Example Usage (Conceptual C++)

Here's a conceptual C++ snippet demonstrating how you might create and interact with a button:


#include <windows.h>

// In your window procedure
case WM_CREATE:
{
    // Create a push button
    HWND hButton = CreateWindow(
        L"BUTTON",                  // Predefined class; can be "BUTTON", "EDIT", "STATIC" etc.
        L"Click Me!",               // Button text
        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,  // Styles
        10, 10,                     // x, y position
        100, 30,                    // width, height
        hwnd,                       // Parent window
        (HMENU)101,                 // Control identifier
        (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
        NULL);                      // Pointer not needed.

    if (hButton == NULL) {
        MessageBox(hwnd, L"Button creation failed!", L"Error", MB_OK | MB_ICONERROR);
        return -1;
    }
}
break;

case WM_COMMAND:
{
    // Check if the message is from our button (ID 101)
    if (LOWORD(wParam) == 101 && HIWORD(wParam) == BN_CLICKED) {
        MessageBox(hwnd, L"Button was clicked!", L"Info", MB_OK | MB_ICONINFORMATION);
    }
}
break;
        

Related API Functions

Function Description
CreateWindow Creates a window or child window. Used for creating button controls.
SendMessage Sends a message to a window or control. Used for sending control-specific messages like BM_CLICK.
GetDlgItem Retrieves a handle to a control in a dialog box. Useful for getting button handles.

Best Practices

When designing UIs with buttons: