您可以定义一个字典来保存映射的所有必要条目并KeyPress
像这样处理事件:
Dictionary<char,char> dict = new Dictionary<char,char>();
//Initialize your dict, this should be done somewhere in your form constructor
dict['L'] = 'N';
dict['A'] = 'B';
//....
//KeyPress event handler for your textBox1
private void textBox1_KeyPress(object sender, KeyPressEventArgs e){
char c;
if(dict.TryGetValue(e.KeyChar, out c)) e.KeyChar = c;
}
注意:为了防止用户粘贴一些不需要的文本,您可以尝试捕获消息WM_PASTE
,从剪贴板获取文本并将更正的文本设置回剪贴板,如下所示:
public class NativeTextBox : NativeWindow {
public Dictionary<char, char> CharMappings;
public NativeTextBox(Dictionary<char,char> charMappings){
CharMappings = charMappings;
}
protected override void WndProc(ref Message m) {
if (m.Msg == 0x302){ //WM_PASTE
string s = Clipboard.GetText();
foreach (var e in CharMappings){
s = s.Replace(e.Key, e.Value);
}
Clipboard.SetText(s);
}
base.WndProc(ref m);
}
}
//Then hook it up like this (place in your form constructor)
new NativeTextBox(dict).AssignHandle(textBox1.Handle);