Why can't I print text in my window when I use SetWindowText()? This is what my window creation code looks like:

game_board[i] = CreateWindowEx(0,
                L"Static",
                board_elements[i],
                WS_CHILD | WS_VISIBLE | WS_BORDER,
                0,
                0,
                0,
                0,
                hwnd,
                (HMENU)IDC_STATICBOARD + i + 1,
                hInst,
                NULL);

And when I write something like:

wchar_t c;
for(i = 0; i < 15; i++){
   c = 'a' + i;
   SetWindowText(game_board[i], c);
   UpdateWindow(game_board[i]);
   }

my program crashes after I trigger that event.

If I use SetWindowText(game_board[i], L"TEXT"); then it prints TEXT everywhere normally.

I also had these issues with needing to precast everything and I don't know why.

I'm using VS 13 and project is a Windows app written in C++. If I copy the code over in Codeblocks then it pops an error for each cast I created in VS and after I remove them all, then it works normally.

Why? Can anyone help me to fix this?

有帮助吗?

解决方案

The SetWindowText function expects a pointer to a nul-terminated string. But you're trying to pass it a single character.

As a commenter mentioned, this code shouldn't even compile. You mention something about "needing to precast everything". This is likely the problem. Casting is like telling the compiler "don't worry about it, I know what I'm doing". But in this case, you don't. The compiler errors were trying to protect you from making a mistake, you should have listened.

Change the code to look like this:

// Declare a character array on the stack, which you'll use to create a
// C-style nul-terminated string, as expected by the API function.
wchar_t str[2];

// Go ahead and nul-terminate the string, since this won't change for each
// loop iteration. The nul terminator is always the last character in the string.
str[1] = L'\0';

for (i = 0; i < 15; i++)
{
   // Like you did before, except you're setting the first character in the array.
   str[0] = L'a' + i;
   SetWindowText(game_board[i], str);
   UpdateWindow(game_board[i]);
}

Note the L prefix. That indicates to the compiler that you're using a wide character/string—required for the wchar_t type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top