Home | API | MFC | C++ | C | Up

Programming Windows API

Colour Dialog Box Example

//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,150, 150, 250, 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 dialoug box and returns colour selected
InvalidateRect(hwndPanel, NULL, TRUE); //invalidates main window prior to pating
break;
}

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

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

COLORREF ShowColorDialog(HWND hwnd) {
//set up dailog box structure and open choose colour dalog 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;
}

Home | API | MFC | C++ | C | Up
Creating a Simple Window | Common Elements | Data Types and Character Sets | The Device Context | Graphics Device Interface | Displaying Text | Displaying Graphics | Mapping Modes | Keyboard Input | Working with the Mouse | Menus | Child Windows | ScrollBar Control | The Dialog Box | Windows Message Box | Common Dialog Box | Bitmaps | Common Controls | Creating a Toolbar | Multiple Document Interface | Timers | DLL’s | Creating Custom Controls | Owner Drawn Controls | API Hooking and DLL Injection | File Management Functions | String Manipulation | System Information Functions

Last Updated: 17 September 2022