Colour 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.

//Select Colour Dialog Box
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
COLORREF ShowColorDialog(HWND);
HBRUSH hBrush;
#define ID_BUTTON 1
COLORREF gColor = RGB(255, 255, 255);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,PWSTR pCmdLine, int nCmdShow) {

MSG msg ;
WNDCLASS wc = {0};
wc.lpszClassName = TEXT("Color dialog box");
wc.hInstance = hInstance;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc;

RegisterClass(&wc);
CreateWindow( wc.lpszClassName, TEXT("Color dialog box"),WS_OVERLAPPEDWINDOW | WS_VISIBLE,0, 0, 700, 200, 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) {

static HWND hwndPanel;
switch(msg) {
case WM_CREATE:
{
CreateWindow(TEXT("button"), TEXT("Color"),WS_VISIBLE | WS_CHILD ,20, 30, 80, 25,hwnd, (HMENU) ID_BUTTON , NULL, NULL);
case WM_PAINT:
HDC hdc;
RECT rc;
PAINTSTRUCT ps;
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
break;
//Paints window background with colour in hBrush
case WM_ERASEBKGND:
{
hBrush = CreateSolidBrush(gColor);
hdc = (HDC) wParam;
GetClientRect(hwnd, &rc);
FillRect(hdc, &rc, hBrush );
}
return 1l;

break;
}

case WM_COMMAND:
{
gColor = ShowColorDialog(hwnd);//opens dialog box and returns colour selected
InvalidateRect(hwndPanel, NULL, TRUE); //invalidates main window prior to painting
break;
}

case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
}

return DefWindowProc(hwnd, msg, wParam, lParam);
}

COLORREF ShowColorDialog(HWND hwnd) {
//set up dialog box structure and open choose colour dialog box
CHOOSECOLOR cc;
static COLORREF crCustClr[16];
ZeroMemory(&cc, sizeof(cc));
cc.lStructSize = sizeof(cc);
cc.hwndOwner = hwnd;
cc.lpCustColors = (LPDWORD) crCustClr;
cc.rgbResult = RGB(0, 255, 0);
cc.Flags = CC_FULLOPEN | CC_RGBINIT;
ChooseColor(&cc);
return cc.rgbResult;
}