LPCWSTR 无法在 TextOut() 方法上正确转换



整个代码片段...

#include <windows.h>
#include <string>
#include <vector>
using namespace std;
//=========================================================
// Globals.
HWND ghMainWnd = 0;
HINSTANCE ghAppInst = 0;
struct TextObj
{
    string s; // The string object.
    POINT p; // The position of the string, relative to the
    // upper-left corner of the client rectangle of
    // the window.
};
vector<TextObj> gTextObjs;
// Step 1: Define and implement the window procedure.
LRESULT CALLBACK
WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    // Objects for painting.
    HDC hdc = 0;
    PAINTSTRUCT ps;
    TextObj to;
    switch( msg )
    {
        // Handle left mouse button click message.
        case WM_LBUTTONDOWN:
            {
                to.s = "Hello, World.";
                // Point that was clicked is stored in the lParam.
                to.p.x = LOWORD(lParam);
                to.p.y = HIWORD(lParam);
                // Add to our global list of text objects.
                gTextObjs.push_back( to );
                InvalidateRect(hWnd, 0, false);
                return 0;
            }
        // Handle paint message.
        case WM_PAINT:
            {
                hdc = BeginPaint(hWnd, &ps);
                for(int i = 0; i < gTextObjs.size(); ++i)
                TextOut(hdc,
                        gTextObjs[i].p.x,
                        gTextObjs[i].p.y,
                        gTextObjs[i].s.c_str(),
                        gTextObjs[i].s.size());
                        EndPaint(hWnd, &ps);
                return 0;
            }
        // Handle key down message.
        case WM_KEYDOWN:
            {
                if( wParam == VK_ESCAPE )
                DestroyWindow(ghMainWnd);
                return 0;
                // Handle destroy window message.
                case WM_DESTROY:
                PostQuitMessage(0);
                return 0;
            }
    }
    // Forward any other messages we didn't handle to the
    // default window procedure.
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

问题是我收到来自 Visual Studio 2012 的错误,告诉我"const char*"类型的参数与 LPCWSTR 类型的参数不兼容。这发生在以下代码行上:

hdc = BeginPaint(hWnd, &ps);
                for(int i = 0; i < gTextObjs.size(); ++i)
                TextOut(hdc,
                        gTextObjs[i].p.x,
                        gTextObjs[i].p.y,gTextObjs[i].s.c_str(), // <---happens here
                        gTextObjs[i].s.size());
                        EndPaint(hWnd, &ps);
                return 0;

我尝试了转换((LPCWSTR)gTextObjs[i].s.c_str()),但显然这是非常错误的,因为每个字符数组操作一个字节到两个字节?在此更改后还收到了"C4018: '<' : signed/unsigned mismatch"警告。我是 c++ 的新手,考虑到转换是错误的,我对这个错误感到非常迷茫。

我已经在 SO 中查看了一些不同的线程,似乎没有什么可以针对这种特定情况量身定制的(或者我只是不太了解这些线程与我的线程之间的相关性)。

另外,只是为了澄清...转换"有效",但它打印了一些奇怪的日语/中文符号外观文字,并且总是不同的。

TextOut 解析为 TextOutW。这需要 UTF-16 文本。您传递 8 位文本。切换到 wstring 中保存的 UTF-16,或调用 TextOutA。

最新更新