سؤال

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.

هل كانت مفيدة؟

المحلول

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 to ch[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 in wParam.
(Actually, it has a bunch of constructors, one for pretty much everything you'll ever need...)

So all you have to do is:

CString ss(pMsg->wParam);

The constructor will take care of the rest, copying the string pointed to by wParam into the ss type.

نصائح أخرى

According to the documentation, WM_CHAR sends a character code in wParam. 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 bit TCHAR.

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 a wchar_t as its first argument (the second argument, the repetition count, is set to 1 by default). Therefore, to construct a CString out of a WPARAM, you cast the value to wchar_t. The following sample prints "0", confirming that the constructed string is indeed what it is expected to be.

#include <stdio.h>
#include <Windows.h>
#include <cstringt.h>
#include <atlstr.h>
int main ()
{
  WPARAM w = 0x222D;
  CString cs ((wchar_t)w);
  printf ("%d", cs.Compare (L"\x222D"));
}

It will work the same in both _UNICODE and ANSI compilation modes, and is portable across 32 and 64 bitness.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top