C# winform 注音輸入法無法觸發快捷鍵 解決方式

之前在 C# WinForm 自訂義快捷鍵 這篇文章中已經加入快捷鍵了,但是筆者發現如果切換到注音輸入法(有些其他輸入法也會),就會出現選字的介面,而不會觸發快捷鍵。例如設定快捷鍵為 A,如果輸入法切換為注音輸入法,按下 A 時會跳出 ㄇ ,不會觸發按鍵事件。

後來筆者找到一個方法解決,就是透過設定 ImeMode 屬性,在微軟官方說明文件中有提到,可以使用 Close 或是 Off,但是筆者在測試的過程中發現沒有效果
反倒是 ImeMode.Disable 可以成功讓使用者只能輸入英文,如果切換為注音輸入法時也會被鎖定在英文輸入模式。

雖然這樣可以解決快捷鍵無法被觸發的問題,不過如果有其他輸入框則會無法輸入中文,解法也很簡單,只要將需要輸入中文的輸入框設定 ImeMode.NoControl 即可

程式碼範例:
  
// 限制無法切換輸入法來防止無法觸發快捷鍵的情況
this.ImeMode = ImeMode.Disable;

// 其他輸入視窗記得要設定不鎖定輸入法,免得無法輸入中文
textBox.ImeMode = ImeMode.NoControl;
    

其他問題

在網頁版的說明文件中,筆者有切換到 .NET 6 來查看,也有切換到英文模式,但是和在程式中看到的說明不一樣,以下是節錄程式中 ImeMode 列舉的其中一部份
  
namespace System.Windows.Forms
{
    /// 
    ///  Specifies a value that determines the IME (Input Method Editor) status
    ///  of the object when that object is selected.
    /// 
    public enum ImeMode
    {
        /// 
        ///  None. This value indicates "No control to IME". When the IMEMode
        ///  property is set to 0, you can use the IMEStatus function to determine
        ///  the current IME status.
        /// 
        NoControl = 0,

        /// 
        ///  IME on. This value indicates that the IME is on and characters specific
        ///  to Chinese or Japanese can be entered. This setting is valid for
        ///  Japanese, Simplified Chinese, and Traditional Chinese IME only.
        /// 
        On = 1,

        /// 
        ///  IME off. This mode indicates that the IME is off, meaning that the
        ///  object behaves the same as English entry mode. This setting is valid
        ///  for Japanese, Simplified Chinese, and Traditional Chinese IME only.
        /// 
        Off = 2,

        /// 
        ///  IME disabled. This mode is similar to IMEMode = 2, except the value 3
        ///  disables IME. With this setting, the users cannot turn the IME on from
        ///  the keyboard, and the IME floating window is hidden. This setting is
        ///  valid for Japanese IME only.
        /// 
        Disable = 3,
    }
}
    

由此可看到 Disable 是僅限日文輸入法,但是在網頁版的說明文件中說明則是不太一樣

網頁版說明:
  
Disable 	3	輸入法目前暫止。 設定這個選項時,使用者將無法從鍵盤開啟輸入法,而且輸入法浮動視窗是隱藏的。
    

雖然透過測試得知 MSDN 上面的說明是正確的,但這個錯誤有點怪,是時候提 issues 了

留言