2016-01-08 26 views
0

我在WindowForm中有窗体。获取我写在过程中的char的Unicode

我要拍摄被写

我想允许只写1种语言的特定字符(UNICODE)。

作为例子我想在我的程序中只允许英文和希伯来语。

我该怎么做?当别的东西被写了的时候我怎么处理?

我知道有

的OnKeyPress

的onkeydown

但我可以e.handle只有英文字符作为被创作的。

我怎样才能通过unicode或其他任何语言来做任何语言?

回答

2

您可以使用KeyPress并检查字符的范围。您可以检查范围的表例如here

然后代码获取容易(这是所有未经测试):

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    var unicodeValue = (int)e.KeyChar; 
    if(unicodeValue >= 0 && unicodeValue <= 0x024F) // it's latin 
     return; 
    if(unicodeValue >= 0x0590 && unicodeValue <= 0x05FF) // it's hebrew 
     return; 
    // otherwise, don't allow it 
    e.Handled = true; 
} 

你当然可以做一个表和辅助功能(并删除这两个ifs和把它放在一起)但我会把它留给你。

请注意:这不会处理复制&粘贴或其他方式在文本框中输入文本(例如抓取文本框句柄并发送WM_SETTEXT)。

KeyPress如果您想禁止从键盘输入字符,但是您应该始终在TextChanged上验证您的整个输入。

这可能喜欢的东西来完成(再次,没有经过测试和书面正确的堆栈溢出的编辑器,小心轻放):

private bool IsCharAllowed(char c) 
{ 
    var unicodeValue = (int)c; 
    if(unicodeValue >= 0 && unicodeValue <= 0x024F) // it's latin 
     return true; 
    if(unicodeValue >= 0x0590 && unicodeValue <= 0x05FF) // it's hebrew 
     return true; 
    // otherwise, don't allow it 
    return false; 
} 

private bool _parsingText = false; 
private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    // if we changed the text from within this event, don't do anything 
    if(_parsingText) return; 

    var textBox = sender as TextBox; 
    if(textBox == null) return; 

    // if the string contains any not allowed characters 
    if(textBox.Text.Any(x => !IsCharAllowed(x)) 
    {   
     // make sure we don't reenter this when changing the textbox's text 
     _parsingText = true; 
     // create a new string with only the allowed chars 
     textBox.Text = new string(textBox.Text.Where(IsCharAllowed).ToArray());   
     _parsingText = false; 
    } 
} 

你也可以使用正则表达式,但说实话,我我从来没有做过任何非拉丁的unicode正则表达式,所以我无法帮到那里。

PS:由于TextChanged事件我张贴重建,如果有任何非允许的字符整个字符串(这可能会很慢,如果字符串是足够长的时间),我有这个除了KeyPress处理

PS2:再入预防并不是真的必要,因为字符串在重新输入时是正确的,并且不会被修改,但是我们避免了Any()检查(它对字符串的每个字符进行迭代,并且 - 可以 - 如果字符串非常长,则要缓慢)

+0

我正在寻找什么 –

0

您可以使用正则表达式像

RegexOptions options = RegexOptions.None; 
Regex regex = new Regex(@"[^a-zA-Z]+", options);  
tempo = regex.Replace(tempo, @" "); 

,赶上它text_changed事件简单的验证输入的文本预先感谢您。

+1

我看不出如何回答这个问题 – Jcl