0

I am trying to use the TextOut function to paint words on my window, and the following method works fine for me:

HDC hdc = GetDC(windowHandle);
TextOut(hdc, 10, 10, TEXT("Hello World"), 16);
ReleaseDC(windowHandle, hdc);

And this outputs :Hello World

All good so far, however when I do the following method:

HDC hdc = GetDC(windowHandle);
string myString = "Hello World";
TextOut(hdc, 10, 10, myString.c_str(), 16);
ReleaseDC(windowHandle, hdc);

the program outputs: Hello World#$%^&

and the #$%^& part are actually other square symbols that I am not sure how to write on the keyboard. I understand that the forth parameter of the TextOut function is type LPCSTR, and using the .c_str() function after my string should output the LPCSTR variable correctly, and so it does since the program runs, however why do I get teh #$%^& included at the end of Hello World and how might I go about fixing that issue? I do need to use the second method and not the first because my program will generate strings which then I would like to output to my window.

3
  • 1
    @MrTux: Umm, no. Not going to do a thing. @CodeBlocks: Why are you passing 16 as the length of the string when it is not 16 characters long? Aug 21, 2014 at 15:05
  • I do need to use the second method and not the first because my program will generate strings which then I would like to output to my window. Just for your info -- the second method will not work (won't even compile) if you change the character set type of your application to Unicode. The fourth parameter is actually an LPCTSTR, not LPCSTR -- when the build is Unicode, that fourth parameter is supposed to represent a wide character string. A std::string represents non-wide character sequences, thus you need to change it to std::wstring if app is Unicode. Aug 21, 2014 at 15:11
  • Good to note, thanx. I believed that the 16 had to do with the size of the font and so forth, how wrong I was...
    – CodeBlocks
    Aug 21, 2014 at 15:16

1 Answer 1

1

According to the documentation of TextOut (http://msdn.microsoft.com/en-us/library/windows/desktop/dd145133%28v=vs.85%29.aspx) the fith parameter reflects the length of the string. You are saying 16 here, however, it's only 11.

2
  • You are completely right, for some reason I believed that parameter would be the size of the font. Do you happen to know how to modify the font size, maybe type and color also, or anything relative to the font in the this function?
    – CodeBlocks
    Aug 21, 2014 at 15:11
  • See msdn.microsoft.com/en-us/library/windows/desktop/…: CreateFont
    – MrTux
    Aug 21, 2014 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.