Progress Bar Control Example

To create a progress bar control specify PROGRESS_CLASS as the window class and register the class by specifying the ICC_PROGRESS_CLASS bit flag in the accompanying INITCOMMONCONTROLSEX structure.

#include <windows.h> #include <commctrl.h> #pragma comment(lib, "comctl32.lib") #define ID_TIMER 2 #define ID_BUTTON 100 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void CreateControls(HWND); HWND hwndPrgBar; HWND hbtn; int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow) { HWND hwnd; MSG msg; WNDCLASS wc = {0}; wc.lpszClassName = TEXT("Progress bar"); wc.hInstance = hInstance; wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE); wc.lpfnWndProc = WndProc; wc.hCursor = LoadCursor(NULL, IDC_ARROW); RegisterClass(&wc); hwnd = CreateWindow( wc.lpszClassName, TEXT("Progress Bar"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 260, 170, NULL, NULL, hInstance, NULL); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { static int c = 0; switch (msg) { case WM_CREATE: CreateControls(hwnd); return 0; case WM_TIMER: SendMessage(hwndPrgBar, PBM_STEPIT, 0, 0); c++; if (c >= 100) { KillTimer(hwnd, ID_TIMER); SetWindowText(hbtn, TEXT("Start")); EnableWindow(hbtn, TRUE); c = 0; } return 0; case WM_COMMAND: if ((HWND)lParam == hbtn) { if (c == 0) { c = 1; SendMessage(hwndPrgBar, PBM_SETPOS, 0, 0); EnableWindow(hbtn, FALSE); SetWindowText(hbtn, TEXT("In Progress")); SetTimer(hwnd, ID_TIMER, 5, NULL); } } return 0; case WM_DESTROY: KillTimer(hwnd, ID_TIMER); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); } void CreateControls(HWND hwnd) { // Load the progress bar common control. INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_PROGRESS_CLASS; InitCommonControlsEx(&icex); // Create progress bar. hwndPrgBar = CreateWindowEx( 0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE | PBS_SMOOTH, 30, 20, 190, 25, hwnd, NULL, NULL, NULL); // Create button. hbtn = CreateWindow( TEXT("BUTTON"), TEXT("Start"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 85, 90, 85, 25, hwnd, (HMENU)ID_BUTTON, NULL, NULL); // Set progress bar range. SendMessage(hwndPrgBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100)); // Set step increment. SendMessage(hwndPrgBar, PBM_SETSTEP, 1, 0); }