截取中文输入法输入的字符串,更改编码为ANSI

在全英文的XP中,在非unicode的程序中输入的中文会转为“??”。

通过截获WM_IME_COMPOSITION消息得到输入的字符串
ImmGetCompositionStringW得到Unicode
WideCharToMultiByte转换为ANSI


BOOL CchartestDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_IME_COMPOSITION)
{
HIMC hIMC;
HWND hWnd=pMsg->hwnd;
DWORD dwSize;
WCHAR lpWideStr[20];

hIMC = ImmGetContext(hWnd);

dwSize = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);

dwSize += sizeof(WCHAR);

memset(lpWideStr, 0, 20);

//get string in Unicode
ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpWideStr, dwSize);

//transfer to ANSI code
int iSize;
LPSTR pszMultiByte;
int ChineseSimpleAcp = 936;

iSize = WideCharToMultiByte(ChineseSimpleAcp,0,lpWideStr,-1,NULL,0, NULL,NULL);

pszMultiByte = new char[iSize+1]/**sizeof(char)*/;

WideCharToMultiByte(ChineseSimpleAcp, 0, lpWideStr, -1, pszMultiByte, iSize, NULL, NULL );

CString strText = pszMultiByte;

delete pszMultiByte;

ImmReleaseContext(hWnd, hIMC);

return TRUE;
}

return Default();
}

你可能感兴趣的:(c++)