The Button control is a standard Windows element used to initiate an action when clicked.
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.
Button controls can be customized using various styles:
BS_PUSHBUTTON: A standard push button.BS_DEFPUSHBUTTON: A default push button (often has a thicker border).BS_CHECKBOX: A checkbox.BS_AUTOCHECKBOX: A checkbox that automatically changes its state when clicked.BS_RADIOBUTTON: A radio button.BS_AUTORADIOBUTTON: A radio button that automatically changes its state.BS_GROUPBOX: A text label that groups other controls.WS_TABSTOP: Allows the button to receive focus when the user presses the TAB key.WS_DISABLED: Makes the button unresponsive to user input.Applications interact with button controls by sending messages. The most common message is:
BM_CLICK: Programmatically simulates a button click.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;
| 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. |
When designing UIs with buttons:
WS_TABSTOP.BS_DEFPUSHBUTTON) for the most common action in a dialog.