Retrieving QString from TCHAR
My application requires me to obtain the first 7 characters from a window title strip. I've tried the following:
Code:
#include <QWidget>
#include <windows.h>
HWND hChild;
PTSTR pTitle;
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:
Re: Retrieving QString from TCHAR
Code:
WCHAR myTitle[9];
hChild = GetForegroundWindow();
GetWindowTextW( hChild, myTitle, 8);
myTitle[8] = 0;
labelTitle
->setText
( QString::fromUtf16(szTitle
));
Re: Retrieving QString from TCHAR
What about more or less something like this:
Code:
class NativeWindow
: public QWidget{
public:
NativeWindow(WId wid) {
QWidget::create(wid,
false,
false);
// window, initializeWindow, destroyOldWindow }
~NativeWindow() {
QWidget::destroy(false,
false);
// destroyWindow, destroySubWindows }
};
Code:
NativeWindow window(GetForegroundWindow());
labelTitle->setText(window.windowTitle());
Re: Retrieving QString from TCHAR
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.
Re: Retrieving QString from TCHAR
Quote:
Originally Posted by
GTBuilder
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.
Re: Retrieving QString from TCHAR
I've solved the problem. The following code gives me what I want.
Code:
#include <QWidget>
#include <windows.h>
HWND hChild;
PTSTR pTitle;
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.
Re: Retrieving QString from TCHAR
@GTBuilder: Your approach is wrong as it only works for ascii window titles.