//radiobutton demo
#include <windows.h>
#define ID_BLUE 1
#define ID_YELLOW 2
#define ID_RED 3
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HINSTANCE hInstance;
COLORREF bk_color;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,PWSTR lpCmdLine, int nCmdShow) {
HWND hwnd;
MSG msg ;
WNDCLASS wc = {0};
wc.lpszClassName = TEXT("myWindowClass");
wc.hInstance = hInstance;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(0, IDC_ARROW);
hInstance = hInstance;
RegisterClass(&wc);
hwnd = CreateWindow(wc.lpszClassName, TEXT("RadioButton Demo"),WS_OVERLAPPEDWINDOW | WS_VISIBLE,100, 100, 410, 170, 0, 0, hInstance, 0);
while( GetMessage(&msg, NULL, 0, 0)) {
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam) {
PAINTSTRUCT ps;
HBRUSH hBrush;
switch(msg) {
case WM_CREATE:
bk_color = RGB(255, 255, 255);
/*create grouping box and associated buttons.*/
CreateWindow(TEXT("button"), TEXT("Choose colour"), WS_CHILD | WS_VISIBLE | BS_GROUPBOX,50,25,300,70, hwnd, (HMENU) 0, hInstance, NULL);
CreateWindow(TEXT("button"), TEXT("Blue"),WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,70,50,75,30, hwnd, (HMENU) ID_BLUE , hInstance, NULL);
CreateWindow(TEXT("button"), TEXT("Yellow"),WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,145,50,85,30, hwnd, (HMENU) ID_YELLOW , hInstance, NULL);
CreateWindow(TEXT("button"), TEXT("Red"),WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,230,50,75,30, hwnd, (HMENU) ID_RED , hInstance, NULL);
break;
case WM_COMMAND:
/*responds to button click by setting variable bk_color to value of colour associated with radio button */
if (HIWORD(wParam) == BN_CLICKED) {
switch (LOWORD(wParam)) {
case ID_BLUE:
bk_color = RGB(0, 76, 255);
break;
case ID_YELLOW:
bk_color = RGB(255, 255, 0);
break;
case ID_RED:
bk_color = RGB(255, 0, 0);
break;
}
HDC hdc;
hdc=GetDC(hwnd);
SetBkColor(hdc,bk_color);
RECT theRect;
GetClientRect(hwnd, &theRect);
InvalidateRect(hwnd,&theRect,TRUE);
ReleaseDC(hwnd,hdc);
DeleteDC(hdc);
}
break;
case WM_PAINT:
/*set background of window to colour selected by radiobutton selection ie red blue or yellow*/
HDC hdc;
hdc = BeginPaint(hwnd, &ps);
hBrush = CreateSolidBrush(bk_color);
RECT theRect;
GetClientRect(hwnd, &theRect);
FillRect(hdc, &theRect, hBrush);
DeleteObject(hBrush);
EndPaint(hwnd, &ps);
ReleaseDC(hwnd,hdc);
DeleteDC(hdc);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
Last Updated: 17 September 2022