C# WinForms 的空白表單預設無法開啟輸入法錄字視窗,設定 this.ImeMode = ImeMode.NoControl 也無效。經 Microsoft 論壇專家指點,使用 ImmAssociateContext API 將輸入法上下文與視窗關聯,終於喚出輸入法。
if (m.Msg == WM_IME_SETCONTEXT && m.WParam.ToInt32() == 1)
{
ImmAssociateContext(this.Handle, m_hImc);
}
輸入文字時會發送 WM_IME_CHAR 訊息,在此處理即可取得漢字。使用 ImmGetCompositionString 擷取組合字串:
case WM_IME_CHAR:
int size = ImmGetCompositionString(m_hImc, GCS_COMPSTR, null, 0);
size += sizeof(Char);
ImmGetCompositionString(m_hImc, GCS_RESULTSTR, str, size);
sb.Append(str.ToString());
MessageBox.Show(str.ToString());
IntoText();
isShowChina = true;
break;
輸入「為人民服務」,卻輸出「為為人人民民服服務務」。查閱 MSDN 發現:WM_IME_CHAR 訊息包含雙位元組字元,應用程式若傳給 DefWindowProc 會導致雙重處理。
if (m.WParam.ToInt32() == PM_REMOVE)
{
// 處理組合字串
}
測試確認:問題徹底解決,不再出現重複字元。
ImmAssociateContext)WM_IME_CHAR 而非 WM_CHAR 取得中文PM_REMOVE 避免雙重處理ImmGetCompositionString 配合 GCS_RESULTSTR 取得確定字串