PDA

View Full Version : Retrieving QString from TCHAR



GTBuilder
25th March 2008, 11:57
My application requires me to obtain the first 7 characters from a window title strip. I've tried the following:



#include <QWidget>
#include <windows.h>

HWND hChild;
PTSTR pTitle;
QString szTitle;

hChild = GetForegroundWindow();

pTitle = (PTSTR) malloc ( 8 * sizeof (QChar)) ;

int iFlag = GetWindowText( hChild, pTitle, 8);
szTitle = *pTitle;

labelTitle->setText( szTitle);



While szTitle is a buffer of TCHAR, QString is unicode so I set the datatype to QString in line 6.

The above compiles, but line 12 returns 1 and line 15 only prints the first character in the title.

I tried changing line 6 to TCHAR, but then I get a compile error at line 15, "invalid conversion from TCHAR to char *.

An suggestions? :confused:

ChristianEhrlicher
25th March 2008, 12:01
WCHAR myTitle[9];

hChild = GetForegroundWindow();
GetWindowTextW( hChild, myTitle, 8);
myTitle[8] = 0;
labelTitle->setText( QString::fromUtf16(szTitle));

jpn
25th March 2008, 12:07
What about more or less something like this:


class NativeWindow : public QWidget
{
public:
NativeWindow(WId wid) {
QWidget::create(wid, false, false); // window, initializeWindow, destroyOldWindow
}
~NativeWindow() {
QWidget::destroy(false, false); // destroyWindow, destroySubWindows
}
};



NativeWindow window(GetForegroundWindow());
labelTitle->setText(window.windowTitle());

GTBuilder
25th March 2008, 13:03
Thanks for the input, Christian and jpn.

Note that the second argument in GetWindowTitle is a pointer to the buffer, not the buffer itself. Even correcting that unfortunately doesn't seem to work. Using WCHAR still gives compiler errors with type conversions.

Using the NativeWindow class prints a blank line.

jpn
25th March 2008, 13:06
Using the NativeWindow class prints a blank line.
Then perhaps you'll have to pass true as initializeWindow parameter. I don't have access to a Windows machine atm so I cannot test myself, sorry.

GTBuilder
27th March 2008, 17:45
I've solved the problem. The following code gives me what I want.



#include <QWidget>
#include <windows.h>

HWND hChild;
PTSTR pTitle;
QString str;
char cTitle[8];

hChild = GetForegroundWindow();
pTitle = (PTSTR) malloc ( 8 * sizeof (TCHAR)) ;
GetWindowText( hChild, pTitle, 8);


for( int i=0; i<7; i++)
{
cTitle[i] = static_cast<char>( *(pTitle + i));
str.append( cTitle[i]);
}

labelTitle->setText( str);


Not sure how universal such an approach is, but my target platform is specific, so not a problem.

ChristianEhrlicher
28th March 2008, 06:43
@GTBuilder: Your approach is wrong as it only works for ascii window titles.