運行環境:Win10 x64, NetFrameWork 4.8, 做者:烏龍哈里,日期:2019-05-01
fetch
TextBox txbx=new TextBox(); InputMethod.SetIsInputMethodEnabled(txbx, false);//關掉輸入法
//把輸入改爲 overwrite 模式 // fetch TextEditor from myTextBox TextBox txbx=new TextBox(); PropertyInfo textEditorProperty = typeof(TextBox).GetProperty("TextEditor", BindingFlags.NonPublic | BindingFlags.Instance); object textEditor = textEditorProperty.GetValue(txbx, null); // set _OvertypeMode on the TextEditor PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty("_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance); overtypeModeProperty.SetValue(textEditor, true, null);
在 KeyDown 事件裏利用 SelectionStart 來設定,下面例子是限定2個字符
spa
private void TextBox_KeyDown(object sender, KeyEventArgs e) { TextBox txbx = sender as TextBox; //只能有兩個字符 if (txbx.SelectionStart < 2) { e.Handled = false;//false才能經過 } else { e.Handled = true; } }