问题描述
所以 GetWindowText 在 MSDN 上声明如下:
So the GetWindowText is declared on MSDN as follows:
int GetWindowText(
HWND hWnd,
LPTSTR lpString,
int nMaxCount
);
但是为了使代码工作,我们必须将第二个参数声明为
However for the code to work we have to declare the second parameter as
TCHAR[255] WTitle;
然后调用函数GetWindowText(hWnd,Wtitle,255);
LPTSTR 是一个指向 tchar 数组的指针,因此声明 LPTSTR 类似于声明 TCHAR[]?但它不是这样工作的.使用 TCHAR[] 时,程序返回有效的 GetWindowText 结果(它是一个等于标题中符号数的整数).问题是:如何从 TCHAR[] 中获得确切的标题?代码如
and then call the function GetWindowText(hWnd,Wtitle,255);
The LPTSTR is a pointer to an array of tchar, so declaring LPTSTR is similar to declaring TCHAR[]? It doesn't work this way though. When using TCHAR[] the program returns valid GetWindowText result (it is an integer equal to the number of symbols in the title). The question is : how can I get the exact title out of TCHAR[] ? Code like
TCHAR[255] WTitle;
cout<< WTitle;
或
cout<< *Wtitle;
返回数字.如何将其与给定的字符串进行比较?
returns numbers. How can I compare this with a given string?
TCHAR[4] Test= __T("TEST")
if (WTitle == Test) do smth
也不起作用.
推荐答案
好的,先来几个定义.
'T' 类型是将计算为 CHAR(单字节)或 WCHAR(双字节)的定义,具体取决于您是否在构建设置中定义了 _UNICODE 符号.目的是让您使用一组源代码同时针对 ANSI 和 UNICODE.
The 'T' types are definitions that will evaluate to either CHAR (single byte) or WCHAR (double-byte), depending upon whether you've got the _UNICODE symbol defined in your build settings. The intent is to let you target both ANSI and UNICODE with a single set of source code.
定义:
TCHAR title[100];
TCHAR * pszTitle;
...不是等价的.第一个定义了一个包含 100 个 TCHAR 的缓冲区.第二个定义了一个指向一个或多个 TCHAR 的指针,但不指向缓冲区.此外,
...are not equivalent. The first defines a buffer of 100 TCHARs. The second defines a pointer to one or more TCHARs, but doesn't point it at a buffer. Further,
sizeof(title) == 100 (or 200, if _UNICODE symbol is defined)
sizeof(pszTitle) == 4 (size of a pointer in Win32)
如果你有这样的函数:
void foo(LPCTSTR str);
...你可以传入以上两个变量中的任何一个:
...you can pass either of the above two variables in:
foo(title); // passes in the address of title[0]
foo(pszTitle); // passes in a copy of the pointer value
好的,所以您获得数字的原因可能是因为您确实定义了 UNICODE(因此字符很宽),并且您使用的是 cout,它特定于单字节字符.改用 wcout:
OK, so the reason you're getting numbers is probably because you do have UNICODE defined (so characters are wide), and you're using cout, which is specific to single-byte characters. Use wcout instead:
wcout << title;
最后,这些都行不通:
TCHAR[4] Test == __T("TEST") ("==" is equality comparison, not assignment)
if (WTitle == Test) do smth (you're comparing pointers, use wcscmp or similar)
这篇关于TCHAR[]、LPWSTR、LPTSTR 和 GetWindow 文本函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!