Colour Common Dialog Box Example

The Colour Dialog Box is created by initialising a CHOOSECOLOR structure and passing the structure to the ChooseColor function.

The syntax of the ChooseColour function is

BOOL ChooseColor(LPCHOOSECOLOR lpcc );

Where lpcc is a Pointer to the LPCHOOSECOLOR structure that contains information used to initialise the dialog box. When ChooseColor function returns, this structure also contains information about the user's colour selection.

#include <windows.h> #include <commdlg.h> #define ID_BUTTON 1 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); COLORREF ShowColorDialog(HWND); COLORREF gColor = RGB(255,255,255); HBRUSH hBrush = NULL; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; WNDCLASS wc; ZeroMemory(&wc, sizeof(wc)); wc.lpszClassName = TEXT("ColorDialog"); wc.hInstance = hInstance; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpfnWndProc = WndProc; wc.hCursor = LoadCursor(NULL, IDC_ARROW); RegisterClass(&wc); CreateWindow( TEXT("ColorDialog"), TEXT("Choose Colour Example"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 500, 300, NULL, NULL, hInstance, NULL); while(GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; RECT rc; switch(msg) { case WM_CREATE: CreateWindow( TEXT("BUTTON"), TEXT("Choose Colour"), WS_CHILD | WS_VISIBLE, 20, 20, 120, 30, hwnd, (HMENU)ID_BUTTON, NULL, NULL); hBrush = CreateSolidBrush(gColor); return 0; case WM_COMMAND: if(LOWORD(wParam)==ID_BUTTON) { gColor = ShowColorDialog(hwnd); DeleteObject(hBrush); hBrush = CreateSolidBrush(gColor); InvalidateRect(hwnd,NULL,TRUE); } return 0; case WM_ERASEBKGND: hdc = (HDC)wParam; GetClientRect(hwnd,&rc); FillRect(hdc,&rc,hBrush); return 1; case WM_PAINT: hdc = BeginPaint(hwnd,&ps); EndPaint(hwnd,&ps); return 0; case WM_DESTROY: DeleteObject(hBrush); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd,msg,wParam,lParam); } COLORREF ShowColorDialog(HWND hwnd) { CHOOSECOLOR cc; static COLORREF customColours[16]; ZeroMemory(&cc,sizeof(CHOOSECOLOR)); cc.lStructSize = sizeof(CHOOSECOLOR); cc.hwndOwner = hwnd; cc.lpCustColors = customColours; cc.rgbResult = gColor; cc.Flags = CC_FULLOPEN | CC_RGBINIT; if(ChooseColor(&cc)) return cc.rgbResult; return gColor; }