如何更改文本框中的字母?
例如,当用户键入“L”时,将键入“N”。因为我使用axshockwavflash并且需要在flash和c#之间进行连接,因此在flash中有很多单词undefiend用于其他语言而且我必须替换it.i使用text.replace()函数,但它对我的情况不起作用。我用它如下:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text.Replace("ی","ي");
}
答案 0 :(得分:1)
尝试分配:
textBox1.Text = textBox1.Text.Replace("ی","ي");
答案 1 :(得分:1)
请记住,String是不可变的。这意味着当您对其执行.Replace时,原始字符串不会更改。制作副本。因此,只有将文本设置为此新值时,它才有效。就像我在下面做的那样
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace("ی","ي");
}
答案 2 :(得分:0)
您可以定义一个字典来保存映射的所有必要条目,并像这样处理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);