Reputation: 121
I am making a Desktop Application in VS 2019, and trying to print the variable x
with TextOut
. I know the problem is not in the way I'm altering the x variable, because it outputs it correctly with OutputDebugString
. What am I doing wrong with TextOut
?
Here is the relevant part of my code:
case WM_PAINT:
{
float x = 1;
while (x < 100) {
x = x + 0.01;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
std::string s = std::to_string(x);
std::wstring stemp = s2ws(s);
LPCWSTR sw = stemp.c_str();
OutputDebugString(sw);
TextOut(hdc, x * 100, 150, sw, 3);
EndPaint(hWnd, &ps);
}
}
I expect slowly increasing numbers (1.01, 1.02, 1.03, etc. ) that stops at 100, but instead I get a stagnant 1.0
in the window. Any help would be greatly appreciated.
Upvotes: 0
Views: 408
Reputation: 597941
You need to call (Begin|End)Paint()
only one time per WM_PAINT
message. This is because BeginPaint()
clips the drawing region to include only the areas that have been invalidated, and then validates the window. So in your example, the 2nd and subsequent iterations of the loop will not have anywhere to draw since the clipping region will be empty.
You need to move the calls to (Begin|End)Paint()
outside of your loop.
There is also no need to manually convert your std::string
data to std::wstring
, just use the ANSI versions of OutputDebugString()
and TextOut()
and let them convert to Unicode internally for you.
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
float x = 1;
while (x < 100) {
x = x + 0.01;
std::string s = std::to_string(x);
OutputDebugStringA(s.c_str());
TextOutA(hdc, x * 100, 150, s.c_str(), 3);
}
EndPaint(hWnd, &ps);
break;
}
If you really want to use std::wstring
then simply use std::to_wstring()
instead of std::to_string()
:
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
float x = 1;
while (x < 100) {
x = x + 0.01;
std::wstring s = std::to_wstring(x);
OutputDebugStringW(s.c_str());
TextOutW(hdc, x * 100, 150, s.c_str(), 3);
}
EndPaint(hWnd, &ps);
break;
}
Upvotes: 3