Creating a Win32 application with a graphical user interface in C++ requires using the Windows API for handling window creation, messages, and user interactions. Below is a simple example of a Win32 application that creates a main window, a left pane with a trackbar, and a static text control to display the current value of the trackbar.
Here is a basic example of how you can set this up:
#include <windows.h>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) {
// Initialize common controls
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_BAR_CLASSES;
InitCommonControlsEx(&icex);
// Register the window class
const char CLASS_NAME[] = "Win32App";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
"Slider Example",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 300,
NULL, NULL, hInstance, NULL
);
if (!hwnd) {
return 0;
}
ShowWindow(hwnd, nCmdShow);
// Run the message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
static HWND hwndTrack, hwndLabel;
static char textBuffer[50];
switch (uMsg) {
case WM_CREATE: {
hwndTrack = CreateWindowEx(
0, TRACKBAR_CLASS, NULL,
WS_CHILD | WS_VISIBLE | TBS_VERT,
10, 10, 50, 200,
hwnd, NULL, NULL, NULL
);
SendMessage(hwndTrack, TBM_SETRANGE, TRUE, MAKELPARAM(0, 100));
SendMessage(hwndTrack, TBM_SETPOS, TRUE, 0);
hwndLabel = CreateWindowEx(
0, "STATIC", "Slider Value: 0",
WS_CHILD | WS_VISIBLE,
80, 20, 200, 20,
hwnd, NULL, NULL, NULL
);
} break;
case WM_HSCROLL:
case WM_VSCROLL: {
if ((HWND)lParam == hwndTrack) {
int pos = SendMessage(hwndTrack, TBM_GETPOS, 0, 0);
sprintf_s(textBuffer, "Slider Value: %d", pos);
SetWindowText(hwndLabel, textBuffer);
}
} break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
Explanation:
- Initialization: The WinMain function initializes common controls and creates a main window.
- WindowProc Callback: This function handles messages sent to the window. It creates the trackbar and static text during the
WM_CREATE message and updates the text when the trackbar is moved.
- Trackbar and Static Text: When the trackbar changes position,
TBM_GETPOS is used to get the new position, and the text is updated accordingly with SetWindowText.
Ensure you have a development environment set up for Windows API programming with access to the Windows headers and libraries. Compile and run this C++ program to see a simple Win32 GUI application with a slider and a label showing the slider's value.