2014-01-17 66 views
0

整個代碼段正確鑄...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和沒有什麼似乎裁縫這個特定的情況下(或者我只是不太明白這些線程和我的相關性)。 :[

此外,爲了澄清...轉換「作品」,但它打印了一些奇怪的日文/中文符號看起來寫作,它總是不同。

回答

5

TextOut正在解析爲TextOutW。這需要UTF-16文本。你傳遞8位文本。切換到wstring中保存的UTF-16,或者調用TextOutA。