如何将 wParam 转换为 CString?
我有一个来自 WM_KEYDOWN 消息的 pMsg->wParam
,我想将其转换为 CString
。我怎样才能做到这一点?
我尝试过以下代码:
TCHAR ch[2];
ch[0] = pMsg->wParam;
ch[1] = _T('\0');
CString ss(ch);
但它不适用于高 ASCII 字符。
I have a pMsg->wParam
from a WM_KEYDOWN message, and I want to convert it into a CString
. How can I do that?
I have tried the following code:
TCHAR ch[2];
ch[0] = pMsg->wParam;
ch[1] = _T('\0');
CString ss(ch);
but it does not work for high ASCII characters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据文档、
WM_CHAR
在wParam
中发送字符代码。备注部分的第一段表示该代码确实是 Unicode UTF-16 代码点。无论您是为 8 位还是 16 位TCHAR
编译代码,都是如此。CodyGray 的评论在
CString
提供各种构造函数的部分是正确的。您正在寻找的是将wchar_t
作为其第一个参数(第二个参数,重复计数,默认设置为 1)。因此,要从WPARAM
构造CString
,请将值转换为wchar_t
。以下示例打印“0”,确认构造的字符串确实是预期的字符串。它在 _UNICODE 和 ANSI 编译模式下的工作方式相同,并且可跨 32 和 64 位移植。
According to the documentation,
WM_CHAR
sends a character code inwParam
. The first paragraph in the Remarks section says that the code is indeed a Unicode UTF-16 codepoint. This is true whether you are compiling your code for 8 or 16 bitTCHAR
.CodyGray's comment is correct in the part that
CString
supplies a variety of constructors. The one you are looking for is that which takes awchar_t
as its first argument (the second argument, the repetition count, is set to 1 by default). Therefore, to construct aCString
out of aWPARAM
, you cast the value towchar_t
. The following sample prints "0", confirming that the constructed string is indeed what it is expected to be.It will work the same in both _UNICODE and ANSI compilation modes, and is portable across 32 and 64 bitness.
问题是
wParam
包含一个指向字符数组的指针。它不是单个字符,因此您无法像此处尝试那样通过将其分配给ch[0]
来自行创建字符串。事实证明,该解决方案比您预期的要容易得多。
CString
类有一个构造函数,它接受一个指向字符数组的指针,这正是wParam
中的内容。(实际上,它有一堆构造函数,一个几乎可以解决所有问题你永远需要...)
所以你所要做的就是:
构造函数将处理其余的事情,将
wParam
指向的字符串复制到ss
类型。The problem is that
wParam
contains a pointer to an array of characters. It is not a single character, so you can't create the string yourself by assigning it toch[0]
as you're trying to do here.The solution turns out to be a lot easier than you probably expected. The
CString
class has a constructor that takes a pointer to a character array, which is precisely what you have inwParam
.(Actually, it has a bunch of constructors, one for pretty much everything you'll ever need...)
So all you have to do is:
The constructor will take care of the rest, copying the string pointed to by
wParam
into thess
type.