wsprintfW printing only tens?

天大地大妈咪最大 提交于 2021-02-10 04:42:24

问题


I have a trackbar and at some point it's value is supposed to change a text:

case WM_HSCROLL:
    {
        LRESULT pos = SendMessage(trackBar, TBM_GETPOS, 0, 0);
        WCHAR buf[3];
        wsprintfW(buf, L"%ld", pos);

        SetWindowText(trackBarValue, (LPCSTR)buf);
    }
    break;

The trackbar's range goes from 15 to 35. For some reason, only the tens gets printed to the text (As my trackbar's value is between 15 and 19, the text is 1, when my trackbar's value is between 20 and 29, my text is 2, and it becomes 3 as my trackbar's value is between 30 and 35.

Of course, I want my text to show the absolute value of my trackbar, not only its tens!

What should I do?

Edit: After running the debugger, I know that buf DOES become by trackbar's value. The problem seems to be with the SetWindowText line.

Edit: One solution was to change SetWindowText to SetWindowTextW and remove the (LPCSTR) cast. Thanks people.


回答1:


You are casting a wide char string to a simple string, which is wrong. You have to use WideCharToMultiByte, like this:

size_t size = WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);

CHAR *szTo = new CHAR[size];
WideCharToMultiByte(CP_ACP, 0, buf, -1, szTo, size, NULL, NULL);

// don't forget to delete[] szTo

Alternatively, you could define your application as Unicode-compliant, so the SetWindowText macro will resolve to SetWindowTextW:

#define UNICODE
#define _UNICODE
#include <windows.h>



回答2:


LRESULT is defined as LONG_PTR, and whenever PTR appears in a name, you should expect it to be large enough to hold a pointer. Pointers are 4 bytes on 32 Bit and 8 bytes on 64 bit, so an LRESULT won't fit into a long (which is 4 bytes) if you compile for 64 bit. So use wsprintfW(buf, L"%llu", pos)



来源:https://stackoverflow.com/questions/15749241/wsprintfw-printing-only-tens

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!