5 Common Pitfalls in Legacy MFC Applications — Themed Control Colors, the 64-bit Registry, Heap Errors Across DLLs, Building for Windows XP, and Waiting for a Process to Exit
Five problems that keep coming back when you maintain old MFC programs — radio button colors ignored under visual styles, reading the 64-bit registry from a 32-bit app, MFC objects and heap errors across DLL boundaries, C++11 builds that run on Windows XP, and finding a process by image name and waiting for it to exit — with their causes and safe fixes in code.
Windows programs built with MFC live longer than most people expect. Factory equipment control screens, in-house admin tools and device configuration utilities — programs nobody touched because "they just work" — are still in use in many places. The trouble starts when you have to change them or move them to a new environment. The code stays the same, but the operating system, the compiler and the build setup change, and problems appear that were never there before.
This article picks five pitfalls that come up especially often when maintaining legacy MFC applications, and for each one explains why it happens, how to fix it, and what to check after the fix. All code assumes a Visual Studio MFC dialog project and a Unicode build.
At a Glance
| # | Symptom | Root cause | Fix direction |
|---|---|---|---|
| 1 | Radio button text color and background do not change in OnCtlColor |
Visual styles (themes) draw the control themselves | Remove the theme from just that control with SetWindowTheme, or draw it yourself |
| 2 | A registry value "does not exist" on 64-bit Windows | 32-bit apps are subject to WOW64 registry redirection | The KEY_WOW64_64KEY flag |
| 3 | Heap errors after passing a CStringArray to a DLL |
Each module uses its own heap/CRT/MFC | An extension DLL that shares the same CRT and MFC, or pass only plain types |
| 4 | Built with a new Visual Studio, the program will not run on XP | The default toolset does not support XP | The v110_xp/v120_xp/v140_xp/v141_xp toolsets plus API limits |
| 5 | Code that waits for a process to exit hangs or fails | Handle leaks, excessive access rights, infinite waits on the UI thread | Toolhelp32 + OpenProcess(SYNCHRONIZE) + a timeout + a worker thread |
Pitfall 1. Radio Button Colors Do Not Change in OnCtlColor
Symptom
You give the dialog a background color and handle OnCtlColor (WM_CTLCOLOR) so that radio buttons (or check boxes) also appear to have a transparent background. Static text changes as expected, but the radio buttons keep their gray background or their text color does not change.
Cause
When visual styles (themes), introduced with Windows XP, are active, button-type controls are drawn by the common controls library (ComCtl32 version 6) using theme data. MFC projects created with recent versions of Visual Studio use version 6 by default through their manifest.
Radio buttons and check boxes drawn with a theme often do not apply values such as the text color that the parent set in WM_CTLCOLORSTATIC. So the same code can work in an older environment where themes were off and suddenly stop working after a manifest is added or the project is moved to a new template.
Also note that radio buttons and check boxes send WM_CTLCOLORSTATIC to their parent, not WM_CTLCOLORBTN. In MFC's OnCtlColor they arrive with nCtlColor == CTLCOLOR_STATIC.
Fix: Turn Off the Theme for That Control Only
The simplest approach is to call SetWindowTheme only on the controls whose colors you want to change. Passing empty strings as the second and third arguments matches no theme entry, so the control is drawn the classic way without a theme and follows your OnCtlColor settings.
// MyDlg.h
class CMyDlg : public CDialog
{
// ...
protected:
CBrush m_brBack; // background brush shared by the dialog and the controls
virtual BOOL OnInitDialog();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
DECLARE_MESSAGE_MAP()
};
// MyDlg.cpp
#include <uxtheme.h>
#pragma comment(lib, "uxtheme.lib")
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
ON_WM_CTLCOLOR()
END_MESSAGE_MAP()
static const UINT kColoredRadios[] = { IDC_RADIO_AUTO, IDC_RADIO_MANUAL };
BOOL CMyDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_brBack.CreateSolidBrush(RGB(235, 243, 250));
for (UINT id : kColoredRadios)
{
if (CWnd* pCtrl = GetDlgItem(id))
::SetWindowTheme(pCtrl->GetSafeHwnd(), L"", L""); // remove the theme from this control only
}
return TRUE;
}
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
if (nCtlColor == CTLCOLOR_DLG)
return m_brBack;
if (nCtlColor == CTLCOLOR_STATIC)
{
const int id = pWnd->GetDlgCtrlID();
if (id == IDC_RADIO_AUTO || id == IDC_RADIO_MANUAL)
{
pDC->SetTextColor(RGB(0, 70, 140));
pDC->SetBkMode(TRANSPARENT); // do not paint behind the text
return m_brBack; // paint the rest in the dialog's color
}
}
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
A common way to get "transparency" is to return GetStockObject(NULL_BRUSH), but then, when the radio button's text or checked state changes, the old text is often not erased and overlaps the new one. Returning a brush in the same color as the parent, as above, is more reliable. If the background is a gradient or an image, this alone is not enough; consider drawing the control yourself as described below.
Things to Watch
- Controls without a theme look like old-style Windows controls, circles included. If a consistent look across the screen matters, alternatives are keeping the theme and drawing only the text with
NM_CUSTOMDRAW, or drawing the image and text yourself instead of using the control. - Group boxes are also button-type controls and have the same problem.
- After the fix, check that the text is still readable in high-contrast mode and at other DPI scales. Hard-coding colors overrides accessibility settings.
Pitfall 2. A 32-bit App Cannot Read a 64-bit Registry Value
Symptom
A value that you can clearly see in Registry Editor, such as MachineGuid under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography, comes back as "not found" (ERROR_FILE_NOT_FOUND) when a program built as 32-bit reads it on 64-bit Windows. The same code built as 64-bit reads it fine.
Cause: WOW64 Registry Redirection
64-bit Windows runs 32-bit programs on a compatibility layer called WOW64. When a 32-bit program accesses many of the keys under HKLM\SOFTWARE, the operating system automatically redirects it to a 32-bit view under HKLM\SOFTWARE\WOW6432Node. This keeps the settings of 32-bit and 64-bit programs from mixing.
MachineGuid exists only in the 64-bit view, so when a 32-bit program opens the key the ordinary way, it looks at the WOW6432Node side and cannot find the value. That is why the result differs from what you see in Registry Editor, which is a 64-bit program.
Fix: The KEY_WOW64_64KEY Flag
Combine KEY_WOW64_64KEY into the access-rights argument of RegOpenKeyEx with a bitwise OR (|), and a 32-bit program can open the 64-bit view. Conversely, a 64-bit program that wants the 32-bit view uses KEY_WOW64_32KEY.
// Read MachineGuid — same result in 32-bit and 64-bit builds
CString ReadMachineGuid()
{
HKEY hKey = nullptr;
LONG rc = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Microsoft\\Cryptography",
0,
KEY_QUERY_VALUE | KEY_WOW64_64KEY,
&hKey);
if (rc != ERROR_SUCCESS)
{
TRACE(L"RegOpenKeyEx failed: %ld\n", rc);
return CString();
}
wchar_t buf[64] = {};
DWORD type = 0;
DWORD cb = sizeof(buf) - sizeof(wchar_t); // leave room for a terminating null
rc = ::RegQueryValueExW(hKey, L"MachineGuid", nullptr, &type,
reinterpret_cast<LPBYTE>(buf), &cb);
::RegCloseKey(hKey);
if (rc != ERROR_SUCCESS || type != REG_SZ)
{
TRACE(L"RegQueryValueEx failed: %ld (type %lu)\n", rc, type);
return CString();
}
return CString(buf);
}
Things to Watch
- Registry functions return the error code as their return value (LONG), not through
GetLastError(). If you ignore the return value and printGetLastError(), you will see an unrelated value. - A string read with
RegQueryValueExmay not be null-terminated, depending on how it was stored. Zero-initializing the buffer and leaving room for one character, as above, keeps it safe. IsWow64Processtells you whether the current process is running under WOW64. You do not need it in order to useKEY_WOW64_64KEY; on 32-bit Windows the flag is simply ignored.- Separately from the registry, the file system is redirected too. When a 32-bit program accesses
C:\Windows\System32, it is redirected toSysWOW64. If a file "clearly exists but is reported missing," suspect this as well. - For code that writes settings, decide consistently across the whole program whether you write to the 32-bit or the 64-bit view. If only some calls carry the flag, the place you read from and the place you write to drift apart.
Pitfall 3. Passing a CStringArray to a DLL Causes Heap Errors
Symptom
The EXE creates a CStringArray and passes it by reference to a DLL function, which fills it with strings. The function returns normally, but later, when the array is destroyed or refilled, the program crashes with a debug heap warning, an access violation, or a pointer to a value such as 0xFEEEFEEE that marks freed memory.
// The problematic pattern
// DLL
__declspec(dllexport) void GetItemNames(CStringArray& out)
{
out.Add(L"Alpha"); // memory allocated from the DLL's heap
out.Add(L"Beta");
}
// EXE
CStringArray names;
GetItemNames(names);
// ... when names is destroyed, it is freed on the EXE's heap → heap corruption
Cause: Allocation and Deallocation Happen on Different Heaps
CString and CStringArray allocate heap memory internally. If the EXE and the DLL use different CRTs (C runtimes) or MFC libraries, each has its own heap. Typical cases:
- One or both link the CRT and MFC statically (
/MT, "Use MFC in a Static Library") - The EXE and the DLL are built with different Visual Studio versions
- One is built as Debug and the other as Release
When the EXE frees memory that the DLL allocated, it is freeing memory that is not in its own heap, and the heap gets corrupted. The worst part is that the error may not appear on the spot but much later and somewhere else entirely.
Fix 1: Share the Same MFC and CRT with an MFC Extension DLL
If MFC objects must cross the DLL boundary, making the DLL an MFC Extension DLL is the approach MFC intends. An extension DLL uses the same MFC DLL and the same memory allocator as the client application, so a CString allocated on one side can safely be freed on the other.
// Extension DLL project (choose "MFC extension DLL" in the wizard; _AFXEXT is defined)
class AFX_EXT_CLASS CItemProvider
{
public:
void GetItemNames(CStringArray& out) const
{
out.RemoveAll();
out.Add(L"Alpha");
out.Add(L"Beta");
}
};
This approach has conditions:
- Both the EXE and the DLL must be built with "Use MFC in a Shared DLL".
- Both must use the same Visual Studio toolset and the same Debug/Release configuration.
- An extension DLL can only be used from MFC applications. It does not fit a DLL that other languages or non-MFC programs will call.
Fix 2: Pass Only Plain Types Across the Boundary
If another team builds the DLL, if it is hard to align build settings, or if other languages may use the DLL in the long run, the most robust approach is to not pass MFC objects across the boundary at all. Below, the DLL reports strings one at a time through a callback and the EXE copies each into its own heap. No memory crosses the boundary, so it is safe even when build settings differ.
// Shared header (included by both the EXE and the DLL)
typedef void (__stdcall *ItemCallback)(const wchar_t* name, void* context);
extern "C" __declspec(dllexport)
int __stdcall EnumItemNames(ItemCallback callback, void* context);
// DLL implementation
extern "C" __declspec(dllexport)
int __stdcall EnumItemNames(ItemCallback callback, void* context)
{
if (!callback) return -1;
const wchar_t* items[] = { L"Alpha", L"Beta", L"Gamma" };
for (const wchar_t* s : items)
callback(s, context); // only lends the pointer briefly
return static_cast<int>(_countof(items));
}
// EXE usage
static void __stdcall OnItem(const wchar_t* name, void* context)
{
static_cast<CStringArray*>(context)->Add(name); // copied onto the EXE's heap
}
void CMyDlg::LoadNames()
{
CStringArray names;
const int count = EnumItemNames(&OnItem, &names);
TRACE(L"%d items\n", count);
}
If the design really requires handing over memory the DLL allocated, have the DLL also provide a free function (such as FreeItemNames) and make it a rule that callers always release the memory through it.
How to Check
- In Project Properties → C/C++ → Code Generation, confirm that the Runtime Library is the same in the EXE and the DLL (
/MDor/MDd). - In Project Properties → Advanced (or General), confirm that Use of MFC is "Shared DLL" in both.
- Compare
dumpbin /dependents MyApp.exeanddumpbin /dependents MyLib.dllto make sure both modules reference the same MFC and CRT DLLs (for example, the same version ofmfc140u.dll).
Pitfall 4. Built with a New Visual Studio, the Program Will Not Run on Windows XP
Symptom
Some PCs attached to industrial sites or equipment still run Windows XP. You move an old MFC program to a recent Visual Studio and build it, and XP shows "is not a valid Win32 application," or the program fails right after launch with "The procedure entry point could not be located in the DLL."
Cause
Starting with Visual Studio 2012, the default platform toolset does not support XP. Executables built with it record a subsystem version in the PE header that is higher than XP, so XP refuses to run them, and the default Windows SDK headers freely expose post-Vista APIs, so functions that do not exist on XP can get linked in.
Fix: Choose an XP Platform Toolset
In Project Properties → Configuration Properties → General → Platform Toolset, choose the toolset whose name includes "Windows XP".
| Visual Studio | XP toolset | Notes |
|---|---|---|
| 2012 (Update 1 or later) | v110_xp |
C++11 features implemented by the VS 2012 compiler are available |
| 2013 | v120_xp |
|
| 2015 | v140_xp |
|
| 2017 | v141_xp |
The last toolset that supports XP; a deprecated component in later versions |
The XP toolsets use a separate Windows SDK that supports XP (7.1A) and tell the linker to use an XP subsystem version (5.01 for x86, 5.02 for x64). The compiler itself is still that Visual Studio's compiler, so you can use the C++11 features that version supports. Keep in mind, though, that C++11 support in VS 2012 is partial; initializer lists and variadic templates, for example, are not available.
Also Take Care Of
- Pin
_WIN32_WINNTto XP: setting#define _WIN32_WINNT 0x0501intargetver.h(or at the top ofstdafx.h) catches accidental use of post-Vista APIs at compile time. If you change only the toolset and leave this value as is, the build may succeed and still fail on XP with a "procedure entry point" error. - Runtime deployment: if you build with
/MD, the XP PC needs the matching Visual C++ Redistributable installed. Where installing it is difficult, consider/MT(static linking), but check that it does not conflict with the DLL heap issue in Pitfall 3. - Thread-safe static initialization: since VS 2015, initialization of function-local
staticvariables is thread-safe, and this feature is known to cause problems on XP, particularly in DLLs loaded dynamically withLoadLibrary. If you see such symptoms, consider the/Zc:threadSafeInit-option. - Test on a real XP machine: keeping an XP virtual machine around and running the build output on it is the surest check.
How to Check
:: Check the subsystem version (5.01 means it targets XP x86)
dumpbin /headers MyApp.exe | findstr /i "subsystem"
:: See which APIs the program imports (look for functions that XP lacks)
dumpbin /imports MyApp.exe > imports.txt
If imports.txt contains functions introduced in Vista or later, such as GetTickCount64 or InitializeSRWLock, the program will not run on XP.
Pitfall 5. Code That Finds a Process by Image Name and Waits for It to Exit Hangs
Situation
You often need to "wait until xxx.exe exits": an updater waits for the main program to close before replacing files, or a program launches an external tool and reads its results when it finishes. The code you commonly find looks roughly like this.
// Common, but full of problems
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe; pe.dwSize = sizeof(pe);
Process32First(snap, &pe);
while (Process32Next(snap, &pe)) { // skips the first entry
if (_tcscmp(pe.szExeFile, _T("worker.exe")) == 0) {// case-sensitive
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
WaitForSingleObject(h, INFINITE); // no failure check, infinite wait
} // no CloseHandle
}
What Is Wrong
| Problem | Consequence |
|---|---|
Requesting PROCESS_ALL_ACCESS |
OpenProcess fails for processes run by another user or with administrator rights |
Not checking the OpenProcess return value |
Waiting on a NULL handle fails immediately, and the code moves on as if it had waited |
INFINITE wait |
If the target hangs, so does the caller, forever |
| Waiting on the UI thread | The window shows "Not Responding" while waiting |
Missing CloseHandle |
A handle leaks on every call |
Using _tcscmp |
Worker.exe and worker.exe are treated as different names |
A Safer Rewrite
The only access right needed to wait for a process to exit is SYNCHRONIZE. Requesting only what you need greatly reduces failures caused by permissions. Several processes may share the same name, so collect them all, wait for them together, and set a timeout.
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <vector>
// Open handles to every process whose name matches (case-insensitive)
static std::vector<HANDLE> OpenProcessesByName(LPCTSTR exeName)
{
std::vector<HANDLE> handles;
HANDLE snap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE)
return handles;
PROCESSENTRY32 pe = { sizeof(pe) }; // dwSize must be filled in
for (BOOL ok = ::Process32First(snap, &pe); ok; ok = ::Process32Next(snap, &pe))
{
if (_tcsicmp(pe.szExeFile, exeName) != 0)
continue;
HANDLE h = ::OpenProcess(SYNCHRONIZE, FALSE, pe.th32ProcessID);
if (h)
handles.push_back(h);
else
TRACE(_T("OpenProcess(%lu) failed: %lu\n"), pe.th32ProcessID, ::GetLastError());
}
::CloseHandle(snap);
return handles;
}
// true if all exited; false on timeout or failure
bool WaitForProcessesToExit(LPCTSTR exeName, DWORD timeoutMs)
{
std::vector<HANDLE> handles = OpenProcessesByName(exeName);
if (handles.empty())
return true; // nothing is running
bool allExited = false;
if (handles.size() <= MAXIMUM_WAIT_OBJECTS) // at most 64 at once
{
DWORD rc = ::WaitForMultipleObjects(static_cast<DWORD>(handles.size()),
&handles[0], TRUE, timeoutMs);
allExited = (rc != WAIT_TIMEOUT && rc != WAIT_FAILED);
}
for (HANDLE h : handles)
::CloseHandle(h);
return allExited;
}
Using It from an MFC Window: Move the Wait to a Worker Thread
If you wait directly inside a dialog's button handler, messages are not processed while waiting and the window freezes. It is safer to hand the waiting to a worker thread and have it report back with a message when done.
#define WM_APP_WAIT_DONE (WM_APP + 1)
static UINT WaitThreadProc(LPVOID param)
{
HWND hDlg = static_cast<HWND>(param); // pass an HWND, not a CWnd*
const bool done = WaitForProcessesToExit(_T("worker.exe"), 5 * 60 * 1000);
::PostMessage(hDlg, WM_APP_WAIT_DONE, done ? 1 : 0, 0);
return 0;
}
void CMyDlg::OnBnClickedStartWait()
{
GetDlgItem(IDC_START_WAIT)->EnableWindow(FALSE);
AfxBeginThread(WaitThreadProc, GetSafeHwnd());
}
LRESULT CMyDlg::OnWaitDone(WPARAM wParam, LPARAM)
{
GetDlgItem(IDC_START_WAIT)->EnableWindow(TRUE);
SetDlgItemText(IDC_STATUS, wParam ? _T("Exited") : _T("Timed out"));
return 0;
}
// Message map: ON_MESSAGE(WM_APP_WAIT_DONE, &CMyDlg::OnWaitDone)
MFC CWnd objects are tied to the thread that created them, and manipulating the UI through a CWnd* from another thread can cause unexpected errors. Make it a habit to pass only the HWND to worker threads and report results with PostMessage.
Other Things to Know
- A snapshot is the list at the moment it was taken. If the target process has not started yet, it is judged "not running," so if you wait right after launching something, you may need a short retry.
- Process IDs are reused. If you call
OpenProcesslong after getting the list, you may open an unrelated process, so open the handle as soon as you find a match, as above. - If you launched the process yourself, you do not need to find it by name; waiting on the process handle returned by
CreateProcessis the most accurate approach. - If you need the exit code, also request
PROCESS_QUERY_INFORMATION(orPROCESS_QUERY_LIMITED_INFORMATIONon Vista and later) inOpenProcessand callGetExitCodeProcess.
Summary: Maintenance Checklist
- If control colors do not change, first check whether visual styles are on, and remove the theme with
SetWindowTheme(hwnd, L"", L"")only from the controls that need it. - If a 32-bit app reads
HKLM\SOFTWARE, decide which registry view to use and applyKEY_WOW64_64KEY/KEY_WOW64_32KEYconsistently. - Check registry function errors through their return values.
- If MFC objects cross a DLL boundary, confirm that the EXE and the DLL share the same CRT/MFC linkage, toolset and configuration, and pass only plain types where possible.
- If XP support is required, use an
_xptoolset together with_WIN32_WINNT 0x0501, and check the subsystem version and imported APIs withdumpbin. - When waiting for a process to exit, keep to four rules:
SYNCHRONIZEaccess, a timeout, closing handles, and a worker thread.
Problems in legacy MFC programs usually start not with a line or two of code but with a change in the operating system or build environment. Once you know the cause the fix is usually short, but without it you can spend a long time digging in the wrong place. If you need maintenance of old MFC/Win32 programs, a move to a current Visual Studio, or development of a new Windows application, contact Springuptech. We will review your code and build environment with you and suggest a realistic path forward.
※ This article expands on our lead engineer's earlier personal blog posts (in Korean): "[MFC] Radio Button 투명 배경", "32bit application 에서 64bit registry 읽기", "MFC 에서 dll에 CStringArray를 인자 전달시 Heap Violations 에러 발생", "Visual Studio 2012 Update 4 이상에서 XP 용 C++ 11 프로그램 구성", "[MFC] 프로세스를 이미지 이름으로 검색하여 종료를 기다리기".
Jaeyong Roh
Lead engineer at Springuptech · 22 years in software engineering
Have a project related to this topic?
Even if it is just an idea, we will help you work out what is possible.