Home > OS >  SetWindowText with a String and Integer
SetWindowText with a String and Integer

Time:07-20

I'm running a threaded application and monitoring the duration with chrono.

What I'm trying to do is then set the window title to say "Duration: " the time taken.

This is what I have so far but it just makes the window title blank.

// Calculate Duration
int duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();

// Update the window title
std::string windowText = "Duration: "   duration;
SetWindowText(_hwnd, (LPCWSTR)windowText.c_str());

CodePudding user response:

First, there's an issue where you're using pointer arithmetic and expecting string concatenation plus integer-to-string conversion.

The value "Duration: " duration is going to be a pointer that is offset from the start of the "Duration: " string literal by duration bytes. If that is any value outside the range [0,10] then you'll have undefined behavior. In any case, that's not what you're looking for.

You can instead do this:

std::string windowText = "Duration: "   std::to_string(duration);

Second, you also have a problem with the call to SetWindowText which requires a wide string. You are attempting to cast it, but that is invalid. No character conversion takes place. You need to convert the string, OR just use wide strings to begin with:

std::wstring windowText = L"Duration: "   std::to_wstring(duration);
SetWindowText(_hwnd, windowText.c_str());
  •  Tags:  
  • c
  • Related