DoText() Function for C++ text drawing.

killdude69 0 Tallied Votes 265 Views Share

Put the following code in a C++ Header File.
The following function is to make it way more easier to draw text onto the client area of a window.

Now the only thing you need to do is include the C++ Header file containing this function into any C++ Source file and use the following code to dynamically write text onto the screen:

DoText(hwnd, 70, 50, "This is my text!!!");

70 and 50 are the values of the X and Y coordinates of the position to drawm the text in.

Tell me if this way is obsolete, returns errors, or in any other way is not a good thing to use.
Tell me if this helps.

void DoText(HWND hwnd, int x, int y, LPSTR text)
    HDC hdc;
    hdc = BeginPaint(hwnd, &ps);
    TextOut(hdc, x, y, text, strlen(text));
    EndPaint(hwnd, &ps);
William Hemsworth 1,339 Posting Virtuoso

No thanks.. that way is very in-efficient, and doesn't give you the options of text size, font, colour and many other styles. Also, say you want to write 100 lines using that function, you would have constructed 200 un-needed variables and made 200 un-needed function calls.

What I would use is something more like:

static COLORREF oldTextRGB = 0, oldBackRGB = 0xFFFFFF;
void Write(HDC hdc, int x, int y, char *text,
	/* Optional params */ COLORREF txtRGB = oldTextRGB,
	COLORREF backRGB = oldBackRGB, HFONT font = NULL) {

	if (font) SelectObject(hdc, font);
	if (txtRGB != oldTextRGB) {
		SetTextColor(hdc, txtRGB);
		oldTextRGB = txtRGB;
	if (backRGB != oldBackRGB) {
		SetBkColor(hdc, backRGB);
		oldBackRGB = backRGB;

	TextOut(hdc, x, y, text, strlen(text));

Even though this may be slightly slower in some cases, it offers many more options and is worth it in the end. But to be honest I think I would just do it all manually to save time and problems :P

killdude69 8 Light Poster

Well, thank you WilliamHemsWorth for your contribution to my snippet. I did not know the options, I just thought it might help newcomers write out text.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.