打印wchar_t时,SetWindowText会崩溃程序

Ant*_*vić -2 c++ windows winapi

为什么我在使用时不能在窗口中打印文字SetWindowText()?这是我的窗口创建代码的样子:

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);
Run Code Online (Sandbox Code Playgroud)

当我写下这样的东西:

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

触发该事件后,我的程序崩溃了.

如果我使用SetWindowText(game_board[i], L"TEXT");它然后通常打印TEXT.

我也有这些问题需要预制一切,我不知道为什么.

我正在使用VS 13,而project是一个用C++编写的Windows应用程序.如果我在Codeblocks中复制代码,那么它会为我在VS中创建的每个强制转换弹出一个错误,在我将它们全部删除后,它会正常工作.

为什么?任何人都可以帮我解决这个问题吗?

Cod*_*ray 5

SetWindowText函数需要一个指向以空字符结尾的字符串的指针.但是你试图把它传给一个角色.

作为一个提到的评论者,这个代码甚至不应该编译.你提到一些关于"需要预制一切"的事情.这可能是问题所在.演员就像告诉编译器"不要担心它,我知道我在做什么".但在这种情况下,你没有.编译器错误试图保护你不犯错误,你应该听.

将代码更改为如下所示:

// 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]);
}
Run Code Online (Sandbox Code Playgroud)

注意L前缀.这向编译器指示您正在使用该wchar_t类型所需的宽字符/字符串.