Home | Up | Email


This page has moved to http://www.dustyant.com/win32. Please update your bookmarks.

Changing Colors

Click here to download the source files for this tutorial.

In this tutorial you will learn to

I will assume that you are familiar with the basics of win32 programming. If you aren't you might want to take a look at my other tutorials here.

Changing the foreground and background color of a window control involves,

  1. Processing the WM_CTLCOLOR* messages
  2. Setting the color through SetBkColor() and SetTextColor() functions

This is done in the callback handler of the parent window. The relevant parts of the code is as follows

int WINAPI
WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow)
{
	...
	
	// Initialise colors
	crEditFg = RGB(0,255,0); // Green ON
	crEditBg = RGB(0,0,0); // Black
	hbrEditBg = CreateSolidBrush(crEditBg);

	crScrollFg = RGB(0,0,0); // Black ON
	crScrollBg = RGB(255,255,0); // Yellow
	hbrScrollBg = CreateSolidBrush(crScrollBg);

	crListFg = RGB(0,0,255); // Blue ON
	crListBg = RGB(255,255,0); // Yellow
	hbrListBg = CreateSolidBrush(crListBg);
... } // Callback function for the Main Window class LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { RECT rc; switch(msg) { ...
	case WM_CTLCOLOREDIT:
		// wParam contains display context
		// lParam contains handle of edit control
		SetBkColor((HDC)wParam, crEditBg); //Make background black
		SetTextColor((HDC)wParam, crEditFg); //Make foreground green
		return (LRESULT)hbrEditBg;
	case WM_CTLCOLORLISTBOX:
		SetBkColor((HDC)wParam, crListBg);
		SetTextColor((HDC)wParam, crListFg);
		return (LRESULT)hbrListBg;
	case WM_CTLCOLORSCROLLBAR:
		SetBkColor((HDC)wParam, crScrollBg);
		SetTextColor((HDC)wParam, crScrollFg);
		return (LRESULT)hbrScrollBg;
... } }

Its as simple as that!

Next, we will take a look at subclassing. Subclassing involves,

  1. Registering the new callback function by passing appropriate parameters to SetWindowLong(?, GWL_WNDPROC, ?) function.
  2. Creating the new callback function.

NOTE: This part of the tutorial has been moved to Lesson 5 - Introducing Subclassing. Click here to go to this lesson.

Previous | Up | Next


Last Updated: February 04, 2003