开发者

Restrict to only English chars

I have a Winform with some edit boxes.

The form can be loaded in 开发者_开发问答other languages too, like chinese! the requirement is that certain textboxes should accept only English chars for Example When user types in Tex box 1, it should be in english Whereas in if he types in Text box 2 and 3 it should be in Chinese ?

Is it possible to do something like this !


Yes, it's certainly possible. You can add a validation event handler that checks the character. You could have a dictionary of permissible characters, or if you restrict the character to a certain encoding (perhaps UTF-8), you could compare the character to a range of characters using < and >.

To be more specific: You can handle the KeyPress event. If e.KeyChar is invalid, set e.Handled to true.

Try this:

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


For handle copy and paste, try the following. It may not be the best solution, but it will trim away 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜