Skip to content

Instantly share code, notes, and snippets.

@ajtruckle
Last active January 31, 2025 15:28
Show Gist options
  • Save ajtruckle/78fae922bc4f981b6cfc6c83ae497ba7 to your computer and use it in GitHub Desktop.
Save ajtruckle/78fae922bc4f981b6cfc6c83ae497ba7 to your computer and use it in GitHub Desktop.
Support MFC Edit Control in Dark Mode
BOOL CTestDarkModeDlg::OnInitDialog()
{
__super::OnInitDialog();
// Snipped other code for berevity
// Set the dark mode theme
SetWindowTheme(GetDlgItem(IDC_EDIT1)->GetSafeHwnd(), L"DarkMode_Explorer", nullptr);
// Tweak to render the border correctly
SetWindowSubclass(GetDlgItem(IDC_EDIT1)->GetSafeHwnd(), EditSubclassProc, 0, 0);
return TRUE;
}
// Declare this function outside of the dialog class.
// Subclass procedure for the CEdit control
static LRESULT CALLBACK EditSubclassProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) {
switch (uMsg) {
case WM_NCPAINT: {
// Draw a custom border
HDC hdc = GetWindowDC(hWnd);
RECT rect;
GetWindowRect(hWnd, &rect);
OffsetRect(&rect, -rect.left, -rect.top);
// Determine the border color
bool hasFocus = (GetFocus() == hWnd);
COLORREF outerBorderColor = RGB(130, 135, 144); // #828790 in RGB
COLORREF innerBorderColor = RGB(240, 240, 240); // Light gray like buttons
COLORREF accentColor = RGB(0, 120, 215); // Example accent color (Windows blue)
// Draw the outer border
HPEN hOuterPen = CreatePen(PS_SOLID, 1, outerBorderColor);
HGDIOBJ hOldPen = SelectObject(hdc, hOuterPen);
HGDIOBJ hOldBrush = SelectObject(hdc, GetStockObject(NULL_BRUSH));
Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);
// Draw the inner border
HPEN hInnerPen = CreatePen(PS_SOLID, 1, innerBorderColor);
SelectObject(hdc, hInnerPen);
InflateRect(&rect, -1, -1); // Shrink the rectangle by 1 pixel
Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);
// Draw the accent color on the bottom edge if focused
if (hasFocus) {
HPEN hAccentPen = CreatePen(PS_SOLID, 2, accentColor);
SelectObject(hdc, hAccentPen);
MoveToEx(hdc, rect.left, rect.bottom - 1, NULL);
LineTo(hdc, rect.right, rect.bottom - 1);
SelectObject(hdc, hInnerPen); // Restore inner pen
DeleteObject(hAccentPen);
}
// Cleanup
SelectObject(hdc, hOldPen);
SelectObject(hdc, hOldBrush);
DeleteObject(hOuterPen);
DeleteObject(hInnerPen);
ReleaseDC(hWnd, hdc);
return 0;
}
case WM_SETFOCUS:
case WM_KILLFOCUS:
// Redraw the non-client area when focus changes
RedrawWindow(hWnd, NULL, NULL, RDW_FRAME | RDW_INVALIDATE);
break;
case WM_DESTROY:
// Remove the subclass when the control is destroyed
RemoveWindowSubclass(hWnd, EditSubclassProc, uIdSubclass);
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment