Category Archives: MFC

Changing Background Color in a CStatic Object

Here’s a classic example of a seemingly easy problem actually being harder to implement.  I wanted a dialog with white static controls in MFC.  The resulting code is simple but divining the answer was no easy feat.  Ultimately it’s more a failure of documentation that it is a engineering challenge.  More details in my commented code which follows:

Before and After
Before and After

HBRUSH TReaderDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
HBRUSH hbr = __super::OnCtlColor(pDC, pWnd, nCtlColor);

// For static controls, draw black text on a white
// background (instead of the default Windows
// dialog background color)
if (nCtlColor == CTLCOLOR_STATIC)
// Set the background color to white
// This is a red herring. You will only affect the text
// drawn and the static control is certainly larger than
// the text drawn so you will have the original color
// "leaking" out. (see pic)
//pDC->SetBkColor(RGB(255, 255, 255));

// Set the background mode for the drawn text to
// transparent
// If you use SetBkColor with SetBkMode you will further
// compound the confusion/frustrtion. Using
// SetBkMode(TRANSPARENT) after SetBkColor cancels
// out SetBkColor.

// The real solution is to create a brush with a solid
// white background and return that from this function.
// Also set the background mode to transparent.

static CBrush mBrush(RGB(255, 255, 255)); // Solid white brush.

hbr = mBrush;

// Return a different brush if the default is
// not desired
return hbr;

How to get SetFocus events with Radio Buttons in MFC

Working in MFC today I wanted to know when the user clicked on a radio button so I could change the default button with SetDefID(IDC_LOAD_MEMORY_BTN) but for some reason after adding the event handler for BN_SETFOCUS I never got a notification.  After poking around the radio button’s properties in Visual Studio 2008 I found Notify – changing it from False to True allowed me to start receiving focus events

Preventing Renamed App From Creating New Registry Entry

In Visual Studio 2008, I was using MFC’s registry calls to save my program preferences.  The problem was new builds weren’t using the prior build’s settings. I was adding the build number to the .exe filename and this caused a new key to be created in the registry based on the .exe name and a new set of settings saved therein.  Inspecting CWinApp‘s m_pszAppName and m_pszExeName I saw both were PuffinApp914.  It turns out m_pszAppName is set to the string resource ID AFX_IDS_APP_TITLE if it’s there.  If AFX_IDS_APP_TITLE doesn’t exist then m_pszAppName is set to the .exe filename.  After adding AFX_IDS_APP_TITLE to the project’s string resources m_pszAppName became Puffin and m_pszExeName stayed with PuffinApp914.  The registry calls use m_pszAppName for the key so my problem was solved.