2

How do I change the text color and font background color that is displayed when I use the DrawText() function?

Whenever I use the DrawText() function, I always output a present font as well as a "white" background color. I understand to change the font I must create the HFONT and use SelectObject to set the font, however... I did not find any color options in the CreateFont parameters (searched in msdn): http://msdn.microsoft.com/en-us/library/windows/desktop/dd183499(v=vs.85).aspx

Now, on msdn page for the DrawText() function (http://msdn.microsoft.com/en-us/library/windows/desktop/dd162498(v=vs.85).aspx) I found the following comment:

"The DrawText function uses the device context's selected font, text color, and background color to draw the text. "

And that is all I could find relative to text color and background color. From that sentence, I am unsure if I should be using some other GDI functions to select other objects that specify text color or background color (if those objects exist), nor am I sure if I missed something in the parameters for CreatFont().

QUESTION: How do I change the text color and font background color that is displayed when I use the DrawText() function?

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
CodeBlocks
  • 233
  • 3
  • 5
  • 14
  • If you are using Microsoft Foundation Classes, check this out for text color: http://msdn.microsoft.com/en-us/library/wf4k5sew.aspx – Logicrat Aug 23 '14 at 22:56
  • Awesome thanks! I saw that there is another function with the same name but 2 parameters (HDC, COLORREF), how come the function your link points to only has a COLORREF? does it make the set colorref universal for all Device Contexts? – CodeBlocks Aug 23 '14 at 23:01
  • in MFC, the CDC class is a wrapper for HDC. The CDC class has a member for HDC, so CDC class objects implicitly contain HDC within their structure. – Logicrat Aug 23 '14 at 23:14
  • You change the text or background colour for the DC you're drawing onto. – chris Aug 23 '14 at 23:42
  • 8
    You can set text color with [`SetTextColor`](http://msdn.microsoft.com/en-us/library/windows/desktop/dd145093%28v=vs.85%29.aspx) API. Text background color can be set with [`SetBkColor`](http://msdn.microsoft.com/en-us/library/windows/desktop/dd162964%28v=vs.85%29.aspx) API. However, if your window has **bitmap image as background**, and you need to make text red for example, and text's background / gaps same as window bitmap, then you must use [`SetBkMode`](http://msdn.microsoft.com/en-us/library/windows/desktop/dd162965%28v=vs.85%29.aspx) API with `TRANSARENT` argument passed. – AlwaysLearningNewStuff Aug 24 '14 at 00:52

1 Answers1

0

You can use the following

private static extern bool SetTextColor(IntPtr hdc, int crColor)

from the library gdi32.dll. Just pass a handle to the window and an integer in the format like so:

0xFFFFFF
Aymendps
  • 1,346
  • 4
  • 20
Dumbelfo
  • 11
  • 1