Barış Uşaklı
Barış Uşaklı

Reputation: 13532

Using WM_GETTEXT to get window title

Trying to get the title of a win32 window with the following code and then trying to change the same windows title using wostringstream. Here is the code to get the title

std::wstring Window::getTitle()const
{
    int length = SendMessage(hwnd,WM_GETTEXTLENGTH,0,0);
    if(length == -1)
        return L"";
    wchar_t* buffer = new wchar_t[length+1];
    SendMessage(hwnd,WM_GETTEXT,length+1,(LPARAM)buffer);
    std::wstring str(buffer);
    delete[] buffer;

    return str;
}

Here is the code that tries to use this :

std::wostringstream oss;

while(window->isRunning)
{

    oss.str(L"");

    oss<<window->getTitle()<<" FPS : "<<100<<" Frame Time"<<100;
    window->setText(oss.str());
}

Instead of displaying the window title plus the frs and the frame time what ends up happening is it displays the window title and then repeats the FPS and Frame time text multiple times. I tried adding a '\0' at the end of buffer with :

buffer[length] = '\0';

Which didn't fix the problem. If I return L"some title" from getTitle everything works correctly, so I am thinking the problem is inside the getTitle function.

Upvotes: 4

Views: 5089

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 134125

Of course the string is going to be repeated. You're getting the window text, adding the FPS and Frame Time, and then setting the window text to the modified string. The next time you call getTitle, it's going to return the modified string.

So I would expect that if you start with a window title of foo, the first two iterations of your loop will result in:

foo FPS : 100 Frame Time100
foo FPS : 100 Frame Time100 FPS : 100 Frame Time100

You'll have to strip the FPS and Frame Time values from the title when you get it from getTitle. Otherwise you'll have an infinitely growing title.

Upvotes: 3

Related Questions