Limit English characters only

I have Winform with some edit fields.

The form can be downloaded in other languages, for example, in Chinese! the requirement is that certain text fields should only accept English characters for example. When a user enters Tex 1 in a box, he must be in English If, if he types in text field 2 and 3, he must be in Chinese?

Is it possible to do something like this!

+6
c # winforms
source share
2 answers

Yes, of course it is possible. You can add a validation event handler that validates a character. You may have a dictionary of valid characters, or if you restrict a character to a specific encoding (possibly UTF-8), you can compare a character with a range of characters using < and > .

More specifically: you can handle the KeyPress event. If e.KeyChar invalid, set e.Handled to true .

Try the following:

 private void textBox_KeyPress(object sender, KeyPressEventArgs e) { if (System.Text.Encoding.UTF8.GetByteCount(new char[] { e.KeyChar }) > 1) { e.Handled = true; } } 
+3
source share

To copy and paste a descriptor, try the following. This may not be the best solution, but it will trim non-UTF8 char.

  private void Control_KeyDown(object sender, KeyEventArgs e) { //Prevent the user from copying text that contains non UTF-8 Characters if (!e.Control || e.KeyCode != Keys.V) return; if (Clipboard.ContainsText() && Clipboard.GetText().Any(c => System.Text.Encoding.UTF8.GetByteCount(new[] {c}) > 1)) { char[] nonUtf8Characters = Clipboard.GetText().Where(c => System.Text.Encoding.UTF8.GetByteCount(new[] {c}) <= 1).ToArray(); if (nonUtf8Characters.Length > 0) { Clipboard.SetText(new String(nonUtf8Characters)); } else { Clipboard.Clear(); } e.Handled = true; } } 
0
source share

All Articles