SendMessage in win32 project has different result - c++

I have a win32 project that has 2 text windows(inputArea, outputArea) and 2 buttons(sendButton and ResetButton).
My problem is that when I press Reset I want to clear the text from both areas, and the inputArea gets cleared but the outputArea gets colored.
Here is the code I have tried:
case IDC_ResetButton:
{
SendMessage(hwndInputArea, WM_SETTEXT, NULL, NULL);
SendMessage(hwndOutputArea, WM_SETTEXT, NULL, NULL);
break;
}
my intial inputArea:
my initial outputArea:
And here is what happens to outputArea when I press Reset:
Also, I tried each line of code separately and they work, but when I put both of them I get this result of the outputArea and I can't find out why.
Thank you in advance.

I guess that is editcontrol.
There are three options of color for that.
・text color
・background color
・drawing brush
HBRUSH CXxxDlg::OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor ) {
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
pDC->SetTextColor(RGB(0,0,0));
pDC->SetBkColor(RGB(192,192,192)); // …(1)
HBRUSH hbrOrg = static_cast<HBRUSH>(GetStockObject(GRAY_BRUSH)); // …(2)
return hbrOrg;
}
(1)(2)… make the same color

try to get the handle of you edit control each time on your button case like this (Change IDC_EDIT1 and 2 to your edit control ID):
case IDC_ResetButton:
{
hwndInputArea = GetDlgItem(hwndDlg,IDC_EDIT1);
hwndOutputArea = GetDlgItem(hwndDlg,IDC_EDIT2);
SendMessage(hwndInputArea, WM_SETTEXT, 0, NULL);
SendMessage(hwndOutputArea, WM_SETTEXT, 0, NULL);
break;
}

Related

Mfc CComboBoxEx - How to change the background color

I have a class that is derived from CComboBoxEx and I'm trying to change the background color. I was thinking that it would work like a ComboBox (using the SetBkColor function), but it doesn't change the background color.
Here's what I have tried :
BEGIN_MESSAGE_MAP(CMyComboBoxEx, CComboBoxEx)
ON_WM_CTLCOLOR()
END_MESSAGE_MAP()
void CMyComboBoxEx::SetBkColor(COLORREF backgroundColor)
{
m_backgroundColor = backgroundColor;
m_brBkgnd.DeleteObject();
m_brBkgnd.CreateSolidBrush(backgroundColor);
}
HBRUSH CMyComboBoxEx::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH brush = __super::OnCtlColor(pDC, pWnd, nCtlColor);
pDC->SetBkColor(RGB(255,0,0));
return brush;
}
I've tried with OnEraseBkgnd() too and it didn't worked either.
Do I need to subclass a derived CComboBox class and set the background color in that class?
Thx.
The problem here is that WM_CTLCOLOR messages are sent to the parent window (dialog box, probably) of your combo control, not to the control itself; also, in the case of the drop-down 'list-box' part of the combo, this message is not sent (as the dialog doesn't need to draw it unless the control has been activated).
The way I have achieved what you want is by making the control owner-draw and then (manually) drawing each item in the list.
First, you need to add the CBS_OWNERDRAWFIXED style to your control in the .rc/.rc2 script; like this, for a typical combo:
COMBOBOX IDC_IGONG, 224, 68, 52,120,
CBS_DROPDOWNLIST | CBS_HASSTRINGS | CBS_OWNERDRAWFIXED | WS_VSCROLL | WS_TABSTOP
Then, you need to add ON_WM_DRAWITEM() to the message map for your dialog class, and override its OnDrawItem() member. Note that the message is sent once for each item in the drop-down list, when the list is made visible by user-action:
void MyDialog::OnDrawItem(int nIDCtl, DRAWITEMSTRUCT *pDIS)
{
switch (pDIS->CtlType) { // You can switch on the ID if it's only one combo!
case ODT_COMBOBOX:
DrawDropDownBox(this, nIDCtl, pDIS);
break;
default:
CDialogEx::OnDrawItem(nIDCtl, pDIS);
break;
}
}
The DrawDropDownBox() does all the hard work:
void MyDialog::DrawDropDownBox(CWnd *box, int nID, DRAWITEMSTRUCT *pDIS)
{
CComboBox *pCBC = dynamic_cast<CMyComboBoxEx *>(box->GetDlgItem(nID));
if (pCBC == nullptr) return; // Skip if we can't get handle to the control
CDC *pDC = CDC::FromHandle(pDIS->hDC);
wchar_t buffer[4096]; // Or just char if you ain't using Unicode
if (pCBC->GetLBText(int(pDIS->itemID), buffer) == CB_ERR) return; // Maybe called during WM_DELETEITEM
int dcSave = pDC->SaveDC(); // Save DC state for later restoration
CPen pen(PS_SOLID, 0, ListColor); // ListColor is COLORREF for your desired b/g
if (pDIS->itemState & ODS_DISABLED) {
pDC->SelectStockObject(NULL_PEN);
pDC->SelectObject(BackBrush); // A CBrush for disabled: defined/created elsewhere
pDC->SetBkMode(TRANSPARENT);
}
else {
pDC->SelectObject(&pen);
pDC->SelectObject(ListBrush); // A CBrush that draws your desired b/g
pDC->SetBkMode(OPAQUE);
}
CRect rc(pDIS->rcItem); pDC->Rectangle(&rc); // This draws the b/g
if (pDIS->itemState & ODS_DISABLED) {
pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT));
}
else if (pDIS->itemState & ODS_SELECTED) { // Use Windows defaults if selected...
pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT));
pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT));
}
else {
pDC->SetTextColor(GetSysColor(COLOR_WINDOWTEXT));
pDC->SetBkColor(ListColor); // Custom b/g color
}
unsigned format = DT_SINGLELINE | DT_VCENTER; // You desired text alignment
pDC->DrawText(CString(buffer), rc, format);
pDC->RestoreDC(dcSave); // Restore DC's saved state...
pDC->Detach(); // ...then 'release it'
return;
}
The code shown handles both disabled combos and selected items in the list; you could possibly skip some of these, if you want to simplify the operation.
Feel free to ask for further explanation and/or clarification.
If it's all about just changing Bk color of the control, then you have to handle WM_CTLCOLOR message in control's parent window:
HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (pWnd->GetDlgCtrlID() == IDC_MY_CONTROL)
{
pDC->SetBkColor(RGB(0, 0, 0)); //Black color
hbr = m_hbrBlack; //Black brush.
}
return hbr;
}
Otherwise, you have to draw your control totally yourself in your derived class, with CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE style, which is way more complicated, but ofc possible.
I'm surprised that all the answers you've got so far suggest either handling WM_CTLCOLOR in parent window or use one of OWNERDRAW styles.
Handling WM_CTLCOLOR in parent window means you'll need to duplicate that code in each parent window's class where you'll use such combobox. This is obviously a bad solution if you want to use combobox more than once.
Adding OWNERDRAW style may have impact on other existing controls that you'd like to subclass and you may need to handle additional problems. That's also far from a sinmple solution.
Fortunately, there's another way to solve it - use Message Reflection. And all you need to do is to add ON_WM_CTLCOLOR_REFLECT() entry to the message map and CtlColor handler.
In case of combobox control I'd do it like this:
MyComboBoxEx.h
class CMyComboBoxEx : public CComboBoxEx
{
public:
CMyComboBoxEx();
virtual ~CMyComboBoxEx();
protected:
CBrush m_BkBrush;
DECLARE_MESSAGE_MAP()
public:
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
};
MyComboBoxEx.cpp
CMyComboBoxEx::CMyComboBoxEx()
{
m_BkBrush.CreateSolidBrush(RGB(0, 255, 0));
}
CMyComboBoxEx::~CMyComboBoxEx()
{
}
BEGIN_MESSAGE_MAP(CMyComboBoxEx, CComboBoxEx)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_CTLCOLOR()
END_MESSAGE_MAP()
HBRUSH CMyComboBoxEx::CtlColor(CDC* pDC, UINT nCtlColor)
{
pDC->SetTextColor(RGB(255, 0, 0));
pDC->SetBkColor(RGB(0, 255, 0));
return m_BkBrush;
}
HBRUSH CMyComboBoxEx::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
return CtlColor(pDC, nCtlColor);
}
Here's how such combobox looks:
If you want to have custom color for borders and glyph then you need to handle WM_PAINT yourself.

How to set textcolor of menu item in mfc

I want to change text color of menu in mfc. I have searched a lot but didn't got a proper solution. Finally I was trying to use OnCtlColor which I generally use for setting the color of static text control. But I am confused here how to do the same for menu items because pWnd->GetDlgCtrlID() dont work on menu.My menu item id is ID_MENU_ITEM. My query is what should i write at "?" to get my job done. And if my approach is wrong please suggest me good alternative.
HBRUSH CMyClass::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr;
if ( ? == ID_MENU_ITEM)
{
pDC->SetTextColor(RGB(255, 0, 0));
hbr = (HBRUSH)m_whitebrush;
return hbr;
}
}

Change Color of read only CEdit control Artifacts and Text Highlighting issue

I have an Edit control that is read only that has text in it. I would like to switch the default gray background to white but have been having limited luck. In my first go, I was executing the following code during initialization of the dialog:
CEdit *m_ctrlEditOne = (CEdit*) GetDlgItem(IDC_EDIT1);
CDC *m_ctrlEEditWee = m_ctrlEditOne->GetDC();
m_ctrlEEditWee->SetBkColor(RGB(255,0,0));
Invalidate(true);
Another solution I tried was:
HBRUSH CTestingDlg::OnCtlColor(CDC* pDC, CWnd *pWnd, UINT nCtlColor)
{
if (pWnd->GetStyle() & ES_READONLY)
//if(pDC->GetRuntimeClass == & ES_READONLY)
{
switch (nCtlColor)
{
case CTLCOLOR_STATIC:
pDC->SetBkColor(RGB(255,255,255));
return (HBRUSH)GetStockObject(NULL_BRUSH);
default:
//return NULL;
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
}
//return NULL;
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
In the screenshot below, you can see that the text is inserted after the fact (this is what needs to happen) and appears highlighted in blue - I have no idea where to begin on how to make it just appear as normal, non-highlighted text. When clicking on it, it appears normally. In the bottom left corners of each edit control, one can see a square which should not be appearing there. Also, you can see some artifacts of what looks like to be a combo box dropdown selection appearing in the larger boxes.
I would appreciate any pointers on how to get rid of the artifacts and fix the highlighting issue with inserted text.
I do as shown below. It will change the background of the read only edit control IDC_EDIT1 to white. This is a copy-paste straight out of one of my projects.
m_whitebrush is a private member of CTestOnCtlClorDlg of type HBRUSH and must be initialized to NULL in the constructor of CTestOnCtlClorDlg.
HBRUSH CTestOnCtlClorDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
int id = pWnd->GetDlgCtrlID( ) ;
if (id == IDC_EDIT1)
{
pDC->SetTextColor(RGB(0, 0, 0));
pDC->SetBkColor(RGB(255,255,255));
if (!m_whitebrush)
m_whitebrush = CreateSolidBrush(RGB(255,255,255)) ;
hbr = m_whitebrush ;
}
return hbr;
}
void CTestOnCtlClorDlg::OnDestroy()
{
CDialog::OnDestroy();
if (m_whitebrush !=NULL)
{
DeleteObject(m_whitebrush) ;
m_whitebrush = NULL ;
}
}

Transparent radio button control with themes using Win32

I am trying to make a radio button control with a transparent background using only Win32 when themes are enabled. The reason for doing this is to allow a radio button to be placed over an image and have the image show (rather than the grey default control background).
What happens out of the box is that the control will have the grey default control background and the standard method of changing this by handling either WM_CTLCOLORSTATIC or WM_CTLCOLORBTN as shown below does not work:
case WM_CTLCOLORSTATIC:
hdcStatic = (HDC)wParam;
SetTextColor(hdcStatic, RGB(0,0,0));
SetBkMode(hdcStatic,TRANSPARENT);
return (LRESULT)GetStockObject(NULL_BRUSH);
break;
My research so far indicates that Owner Draw is the only way to achieve this. I've managed to get most of the way with an Owner Draw radio button - with the code below I have a radio button and a transparent background (the background is set in WM_CTLCOLORBTN). However, the edges of the radio check are cut off using this method - I can get them back by uncommenting the call to the function DrawThemeParentBackgroundEx but this breaks the transparency.
void DrawRadioControl(HWND hwnd, HTHEME hTheme, HDC dc, bool checked, RECT rcItem)
{
if (hTheme)
{
static const int cb_size = 13;
RECT bgRect, textRect;
HFONT font = (HFONT)SendMessageW(hwnd, WM_GETFONT, 0, 0);
WCHAR *text = L"Experiment";
DWORD state = ((checked) ? RBS_CHECKEDNORMAL : RBS_UNCHECKEDNORMAL) | ((bMouseOverButton) ? RBS_HOT : 0);
GetClientRect(hwnd, &bgRect);
GetThemeBackgroundContentRect(hTheme, dc, BP_RADIOBUTTON, state, &bgRect, &textRect);
DWORD dtFlags = DT_VCENTER | DT_SINGLELINE;
if (dtFlags & DT_SINGLELINE) /* Center the checkbox / radio button to the text. */
bgRect.top = bgRect.top + (textRect.bottom - textRect.top - cb_size) / 2;
/* adjust for the check/radio marker */
bgRect.bottom = bgRect.top + cb_size;
bgRect.right = bgRect.left + cb_size;
textRect.left = bgRect.right + 6;
//Uncommenting this line will fix the button corners but breaks transparency
//DrawThemeParentBackgroundEx(hwnd, dc, DTPB_USECTLCOLORSTATIC, NULL);
DrawThemeBackground(hTheme, dc, BP_RADIOBUTTON, state, &bgRect, NULL);
if (text)
{
DrawThemeText(hTheme, dc, BP_RADIOBUTTON, state, text, lstrlenW(text), dtFlags, 0, &textRect);
}
}
else
{
// Code for rendering the radio when themes are not present
}
}
The method above is called from WM_DRAWITEM as shown below:
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT pDIS = (LPDRAWITEMSTRUCT)lParam;
hTheme = OpenThemeData(hDlg, L"BUTTON");
HDC dc = pDIS->hDC;
wchar_t sCaption[100];
GetWindowText(GetDlgItem(hDlg, pDIS->CtlID), sCaption, 100);
std::wstring staticText(sCaption);
DrawRadioControl(pDIS->hwndItem, hTheme, dc, radio_group.IsButtonChecked(pDIS->CtlID), pDIS->rcItem, staticText);
SetBkMode(dc, TRANSPARENT);
SetTextColor(hdcStatic, RGB(0,0,0));
return TRUE;
}
So my question is two parts I suppose:
Have I missed some other way to achieve my desired result?
Is it possible to fix the clipped button corners issue with my code and still have a transparent background
After looking at this on and off for nearly three months I've finally found a solution that I'm pleased with. What I eventually found was that the radio button edges were for some reason not being drawn by the routine within WM_DRAWITEM but that if I invalidated the radio button control's parent in a rectangle around the control, they appeared.
Since I could not find a single good example of this I'm providing the full code (in my own solution I have encapsulated my owner drawn controls into their own class, so you will need to provide some details such as whether the button is checked or not)
This is the creation of the radiobutton (adding it to the parent window) also setting GWL_UserData and subclassing the radiobutton:
HWND hWndControl = CreateWindow( _T("BUTTON"), caption, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
xPos, yPos, width, height, parentHwnd, (HMENU) id, NULL, NULL);
// Using SetWindowLong and GWL_USERDATA I pass in the this reference, allowing my
// window proc toknow about the control state such as if it is selected
SetWindowLong( hWndControl, GWL_USERDATA, (LONG)this);
// And subclass the control - the WndProc is shown later
SetWindowSubclass(hWndControl, OwnerDrawControl::WndProc, 0, 0);
Since it is owner draw we need to handle the WM_DRAWITEM message in the parent window proc.
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT pDIS = (LPDRAWITEMSTRUCT)lParam;
hTheme = OpenThemeData(hDlg, L"BUTTON");
HDC dc = pDIS->hDC;
wchar_t sCaption[100];
GetWindowText(GetDlgItem(hDlg, pDIS->CtlID), sCaption, 100);
std::wstring staticText(sCaption);
// Controller here passes to a class that holds a map of all controls
// which then passes on to the correct instance of my owner draw class
// which has the drawing code I show below
controller->DrawControl(pDIS->hwndItem, hTheme, dc, pDIS->rcItem,
staticText, pDIS->CtlID, pDIS->itemState, pDIS->itemAction);
SetBkMode(dc, TRANSPARENT);
SetTextColor(hdcStatic, RGB(0,0,0));
CloseThemeData(hTheme);
return TRUE;
}
Here is the DrawControl method - it has access to class level variables to allow state to be managed since with owner draw this is not handled automatically.
void OwnerDrawControl::DrawControl(HWND hwnd, HTHEME hTheme, HDC dc, bool checked, RECT rcItem, std::wstring caption, int ctrlId, UINT item_state, UINT item_action)
{
// Check if we need to draw themed data
if (hTheme)
{
HWND parent = GetParent(hwnd);
static const int cb_size = 13;
RECT bgRect, textRect;
HFONT font = (HFONT)SendMessageW(hwnd, WM_GETFONT, 0, 0);
DWORD state;
// This method handles both radio buttons and checkboxes - the enums here
// are part of my own code, not Windows enums.
// We also have hot tracking - this is shown in the window subclass later
if (Type() == RADIO_BUTTON)
state = ((checked) ? RBS_CHECKEDNORMAL : RBS_UNCHECKEDNORMAL) | ((is_hot_) ? RBS_HOT : 0);
else if (Type() == CHECK_BOX)
state = ((checked) ? CBS_CHECKEDNORMAL : CBS_UNCHECKEDNORMAL) | ((is_hot_) ? RBS_HOT : 0);
GetClientRect(hwnd, &bgRect);
// the theme type is either BP_RADIOBUTTON or BP_CHECKBOX where these are Windows enums
DWORD theme_type = ThemeType();
GetThemeBackgroundContentRect(hTheme, dc, theme_type, state, &bgRect, &textRect);
DWORD dtFlags = DT_VCENTER | DT_SINGLELINE;
if (dtFlags & DT_SINGLELINE) /* Center the checkbox / radio button to the text. */
bgRect.top = bgRect.top + (textRect.bottom - textRect.top - cb_size) / 2;
/* adjust for the check/radio marker */
// The +3 and +6 are a slight fudge to allow the focus rectangle to show correctly
bgRect.bottom = bgRect.top + cb_size;
bgRect.left += 3;
bgRect.right = bgRect.left + cb_size;
textRect.left = bgRect.right + 6;
DrawThemeBackground(hTheme, dc, theme_type, state, &bgRect, NULL);
DrawThemeText(hTheme, dc, theme_type, state, caption.c_str(), lstrlenW(caption.c_str()), dtFlags, 0, &textRect);
// Draw Focus Rectangle - I still don't really like this, it draw on the parent
// mainly to work around the way DrawFocus toggles the focus rect on and off.
// That coupled with some of my other drawing meant this was the only way I found
// to get a reliable focus effect.
BOOL bODAEntire = (item_action & ODA_DRAWENTIRE);
BOOL bIsFocused = (item_state & ODS_FOCUS);
BOOL bDrawFocusRect = !(item_state & ODS_NOFOCUSRECT);
if (bIsFocused && bDrawFocusRect)
{
if ((!bODAEntire))
{
HDC pdc = GetDC(parent);
RECT prc = GetMappedRectanglePos(hwnd, parent);
DrawFocus(pdc, prc);
}
}
}
// This handles drawing when we don't have themes
else
{
TEXTMETRIC tm;
GetTextMetrics(dc, &tm);
RECT rect = { rcItem.left ,
rcItem.top ,
rcItem.left + tm.tmHeight - 1,
rcItem.top + tm.tmHeight - 1};
DWORD state = ((checked) ? DFCS_CHECKED : 0 );
if (Type() == RADIO_BUTTON)
DrawFrameControl(dc, &rect, DFC_BUTTON, DFCS_BUTTONRADIO | state);
else if (Type() == CHECK_BOX)
DrawFrameControl(dc, &rect, DFC_BUTTON, DFCS_BUTTONCHECK | state);
RECT textRect = rcItem;
textRect.left = rcItem.left + 19;
SetTextColor(dc, ::GetSysColor(COLOR_BTNTEXT));
SetBkColor(dc, ::GetSysColor(COLOR_BTNFACE));
DrawText(dc, caption.c_str(), -1, &textRect, DT_WORDBREAK | DT_TOP);
}
}
Next is the window proc that is used to subclass the radio button control - this
is called with all windows messages and handles several before then passing unhandled
ones on to the default proc.
LRESULT OwnerDrawControl::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
// Get the button parent window
HWND parent = GetParent(hWnd);
// The page controller and the OwnerDrawControl hold some information we need to draw
// correctly, such as if the control is already set hot.
st_mini::IPageController * controller = GetWinLong<st_mini::IPageController *> (parent);
// Get the control
OwnerDrawControl *ctrl = (OwnerDrawControl*)GetWindowLong(hWnd, GWL_USERDATA);
switch (uMsg)
{
case WM_LBUTTONDOWN:
if (controller)
{
int ctrlId = GetDlgCtrlID(hWnd);
// OnCommand is where the logic for things like selecting a radiobutton
// and deselecting the rest of the group lives.
// We also call our Invalidate method there, which redraws the radio when
// it is selected. The Invalidate method will be shown last.
controller->OnCommand(parent, ctrlId, 0);
return (0);
}
break;
case WM_LBUTTONDBLCLK:
// We just treat doubleclicks as clicks
PostMessage(hWnd, WM_LBUTTONDOWN, wParam, lParam);
break;
case WM_MOUSEMOVE:
{
if (controller)
{
// This is our hot tracking allowing us to paint the control
// correctly when the mouse is over it - it sets flags that get
// used by the above DrawControl method
if(!ctrl->IsHot())
{
ctrl->SetHot(true);
// We invalidate to repaint
ctrl->InvalidateControl();
// Track the mouse event - without this the mouse leave message is not sent
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hWnd;
TrackMouseEvent(&tme);
}
}
return (0);
}
break;
case WM_MOUSELEAVE:
{
if (controller)
{
// Turn off the hot display on the radio
if(ctrl->IsHot())
{
ctrl->SetHot(false);
ctrl->InvalidateControl();
}
}
return (0);
}
case WM_SETFOCUS:
{
ctrl->InvalidateControl();
}
case WM_KILLFOCUS:
{
RECT rcItem;
GetClientRect(hWnd, &rcItem);
HDC dc = GetDC(parent);
RECT prc = GetMappedRectanglePos(hWnd, parent);
DrawFocus(dc, prc);
return (0);
}
case WM_ERASEBKGND:
return 1;
}
// Any messages we don't process must be passed onto the original window function
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
Finally the last little piece of the puzzle is that you need to invalidate the control (redraw it) at the right times. I eventually found that invalidating the parent allowed the drawing to work 100% correctly. This was causing flicker until I realised that I could get away by only invalidating a rectangle as big as the radio check, rather than as big as the whole control including text as I had been.
void InvalidateControl()
{
// GetMappedRectanglePos is my own helper that uses MapWindowPoints
// to take a child control and map it to its parent
RECT rc = GetMappedRectanglePos(ctrl_, parent_);
// This was my first go, that caused flicker
// InvalidateRect(parent_, &rc_, FALSE);
// Now I invalidate a smaller rectangle
rc.right = rc.left + 13;
InvalidateRect(parent_, &rc, FALSE);
}
A lot of code and effort for something that should be simple - drawing a themed radio button over a background image. Hopefully the answer will save someone else some pain!
* One big caveat with this is it only works 100% correctly for owner controls that are over a background (such as a fill rectangle or an image). That is ok though, since it is only needed when drawing the radio control over a background.
I've done this some time ago as well. I remember the key was to just create the (radio) buttons as usual. The parent must be the dialog or window, not a tab control. You could do it differently but I created a memory dc (m_mdc) for the dialog and painted the background on that. Then add the OnCtlColorStatic and OnCtlColorBtn for your dialog:
virtual HBRUSH OnCtlColorStatic(HDC hDC, HWND hWnd)
{
RECT rc;
GetRelativeClientRect(hWnd, m_hWnd, &rc);
BitBlt(hDC, 0, 0, rc.right - rc.left, rc.bottom - rc.top, m_mdc, rc.left, rc.top, SRCCOPY);
SetBkColor(hDC, GetSysColor(COLOR_BTNFACE));
if (IsAppThemed())
SetBkMode(hDC, TRANSPARENT);
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
virtual HBRUSH OnCtlColorBtn(HDC hDC, HWND hWnd)
{
return OnCtlColorStatic(hDC, hWnd);
}
The code uses some in-house classes and functions similar to MFC, but I think you should get the idea. As you can see it draws the background of these controls from the memory dc, that's key.
Give this a try and see if it works!
EDIT: If you add a tab control to the dialog and put the controls on the tab (that was the case in my app) you must capture it's background and copy it to the memory dc of the dialog. It's a bit of an ugly hack but it works, even if the machine is running some extravagant theme that uses a gradient tab background:
// calculate tab dispay area
RECT rc;
GetClientRect(m_tabControl, &rc);
m_tabControl.AdjustRect(false, &rc);
RECT rc2;
GetRelativeClientRect(m_tabControl, m_hWnd, &rc2);
rc.left += rc2.left;
rc.right += rc2.left;
rc.top += rc2.top;
rc.bottom += rc2.top;
// copy that area to background
HRGN hRgn = CreateRectRgnIndirect(&rc);
GetRelativeClientRect(m_hWnd, m_tabControl, &rc);
SetWindowOrgEx(m_mdc, rc.left, rc.top, NULL);
SelectClipRgn(m_mdc, hRgn);
SendMessage(m_tabControl, WM_PRINTCLIENT, (WPARAM)(HDC)m_mdc, PRF_CLIENT);
SelectClipRgn(m_mdc, NULL);
SetWindowOrgEx(m_mdc, 0, 0, NULL);
DeleteObject(hRgn);
Another interesting point, while we're busy now, to get it all non-flickering create the parent and children (buttons, statics, tabs etc) with the WS_CLIPCHILDREN and WS_CLIPSIBLINGS style. The the order of creation is essential: First create the controls you put on the tabs, then create the tab control. Not the other way around (although it feels more intuitive). That because the tab control should clip the area obscured by the controls on it :)
I can't immediately try this out, but so far as I recall, you don't need owner draw. You need to do this:
Return 1 from WM_ERASEBKGND.
Call DrawThemeParentBackground from WM_CTLCOLORSTATIC to draw the background there.
Return GetStockObject(NULL_BRUSH) from WM_CTLCOLORSTATIC.
Knowing the sizes and coordinates radio button, we will copy the
image to them closed.
Then we create a brush by means of
BS_PATTERN style CreateBrushIndirect
Farther according to the
usual scheme - we return handle to this brush in reply to COLOR -
the message (WM_CTLCOLORSTATIC).
I have no idea why you are doing it so difficult, this is best solved via CustomDrawing
This is my MFC Handler to draw a Notebook on a CTabCtrl control. I'm not really sure why i need to Inflate the Rectangle, because if i don't do it a black border is drawn.
And another conceptional bug MS made is IMHO that i have to overwrite the PreErase drawing phase instead of the PostErase. But if i do the later the checkbox is gone.
afx_msg void AguiRadioButton::OnCustomDraw(NMHDR* notify, LRESULT* res) {
NMCUSTOMDRAW* cd = (NMCUSTOMDRAW*)notify;
if (cd->dwDrawStage == CDDS_PREERASE) {
HTHEME theme = OpenThemeData(m_hWnd, L"Button");
CRect r = cd->rc; r.InflateRect(1,1,1,1);
DrawThemeBackground(theme, cd->hdc, TABP_BODY, 0, &r,NULL);
CloseThemeData(theme);
*res = 0;
}
*res = 0;
}

MFC - change text color of a cstatic text control

How do you change the text color of a CStatic text control? Is there a simple way other that using the CDC::SetTextColor?
You can implement ON_WM_CTLCOLOR in your dialog class, without having to create a new CStatic-derived class:
BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
//{{AFX_MSG_MAP(CMyDialog)
ON_WM_CTLCOLOR()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd *pWnd, UINT nCtlColor)
{
switch (nCtlColor)
{
case CTLCOLOR_STATIC:
pDC->SetTextColor(RGB(255, 0, 0));
return (HBRUSH)GetStockObject(NULL_BRUSH);
default:
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
}
Notice that the code above sets the text of all static controls in the dialog. But you can use the pWnd variable to filter the controls you want.
unfortunately you won't find a SetTextColor method in the CStatic class. If you want to change the text color of a CStatic you will have to code a bit more.
In my opinion the best way is creating your own CStatic-derived class (CMyStatic) and there cacth the ON_WM_CTLCOLOR_REFLECT notification message.
BEGIN_MESSAGE_MAP(CMyStatic, CStatic)
//{{AFX_MSG_MAP(CMyStatic)
ON_WM_CTLCOLOR_REFLECT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
HBRUSH CColorStatic::CtlColor(CDC* pDC, UINT nCtlColor)
{
pDC->SetTextColor(RGB(255,0,0));
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
Obviously you can use a member variable and a setter method to replace the red color (RGB(255,0,0)).
Regards.
Just a follow up to the painting issue (a transparent background), which caused by *return (HBRUSH)GetStockObject(NULL_BRUSH);*
Easy change as below:
HBRUSH hBrush = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (nCtlColor == CTLCOLOR_STATIC &&
pWnd->GetSafeHwnd() == GetDlgItem(XXX)->GetSafeHwnd()
) pDC->SetTextColor(RGB(255, 0, 0));
return hBrush;
Hope this helps.
From the Answers given here and other places, it was not obvious how to create a derived class to be used instead of CStatic that handles coloring itself.
So following is what works for me, using MSVS 2013 Version 12.0.40629.00 Update 5. I can place a "Static Text"-control in the resource editor, then replace the type of the member variable with TColorText.
In the .h-file:
class TColorText : public CStatic
{
protected:
DECLARE_MESSAGE_MAP( )
public:
// make the background transparent (or if ATransparent == true, restore the previous background color)
void setTransparent( bool ATransparent = true );
// set background color and make the background opaque
void SetBackgroundColor( COLORREF );
void SetTextColor( COLORREF );
protected:
HBRUSH CtlColor( CDC* pDC, UINT nCtlColor );
private:
bool MTransparent = true;
COLORREF MBackgroundColor = RGB( 255, 255, 255 ); // default is white (in case someone sets opaque without setting a color)
COLORREF MTextColor = RGB( 0, 0, 0 ); // default is black. it would be more clean
// to not use the color before set with SetTextColor(..), but whatever...
};
in the .cpp-file:
void TColorText::setTransparent( bool ATransparent )
{
MTransparent = ATransparent;
Invalidate( );
}
void TColorText::SetBackgroundColor( COLORREF AColor )
{
MBackgroundColor = AColor;
MTransparent = false;
Invalidate( );
}
void TColorText::SetTextColor( COLORREF AColor )
{
MTextColor = AColor;
Invalidate( );
}
BEGIN_MESSAGE_MAP( TColorText, CStatic )
ON_WM_CTLCOLOR_REFLECT( )
END_MESSAGE_MAP( )
HBRUSH TColorText::CtlColor( CDC* pDC, UINT nCtlColor )
{
pDC->SetTextColor( MTextColor );
pDC->SetBkMode( TRANSPARENT ); // we do not want to draw background when drawing text.
// background color comes from drawing the control background.
if( MTransparent )
return nullptr; // return nullptr to indicate that the parent object
// should supply the brush. it has the appropriate background color.
else
return (HBRUSH) CreateSolidBrush( MBackgroundColor ); // color for the empty area of the control
}
Very helpful.
https://msdn.microsoft.com/de-de/library/0wwk06hc.aspx
Alike to
HBRUSH hBrush = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (nCtlColor == CTLCOLOR_STATIC &&
pWnd->GetSafeHwnd() == GetDlgItem(XXX)->GetSafeHwnd()
) pDC->SetTextColor(RGB(255, 0, 0));
return hBrush;
I believe you can't return nullptr for a HBRUSH rather (HBRUSH)GetStockObject(NULL_BRUSH);