Textbox - Validate input before paste

雨燕双飞 提交于 2019-12-23 02:28:05

问题


On my Textbox only accepts Alphanumeric characters and a underscore using the Keypressed event but I am having problems when I right click on the textbox and pasted special characters and accepts it

Is there a way to validate the string from there before clicking paste?

Any answers will help thanks!


回答1:


You may

1- Disable shortcuts for the textbox that would disable Ctrl-C, Ctrl-V, and the second line(will assign a empty context menu, with no items and will override the original context menu) and no context menu will appear (as it has no items):

textBox1.ShortcutsEnabled = false;
textBox1.ContextMenu = new ContextMenu();

2-If you don't want to disable paste option, you may use TextChanged event of the textbox and validate the pasted text there.




回答2:


TextChanged is a bit late, it raises after the text of the control has been changed and results in an awkward user experience.

To have a better user experience, it's better to handle WM_PASTE message and strip disallowed characters and paste the sanitized test on SelectedText. TextChanged event is a bit late and the user experience is not friendly enough, it removes the character after te text property changes which is annoying. By handling WM_PASTE and OnKeyPress you can always keep the caret at the position which is expected by user, sanitize input without any flicker.

Here is an example which allows alphanumeric characters and underscore for a TextBox. On key press, if the character is not allowed, it plays a beep sound. In paste, if the string contains disallowed characters, it strips the characters and paste just valid characters:

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

public class MyTextBox : TextBox
{
    private const int WM_PASTE = 0x0302;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool MessageBeep(int type);
    protected override void WndProc(ref Message m)
    {
        if (m.Msg != WM_PASTE) { base.WndProc(ref m); }
        else
        {
            var text = SanitizeText(Clipboard.GetText());
            SelectedText = text;
        }
    }
    protected virtual string SanitizeText(string value)
    {
        return Regex.Replace(value ?? "", @"[^a-zA-Z0-9_]", "");
    }
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        var input = e.KeyChar;
        var allowedChars = new char[] { '_', '\b' };
        if (((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) |
            Char.IsLetterOrDigit(e.KeyChar) |
            allowedChars.Contains(input))
        {
            base.OnKeyPress(e);
        }
        else
        {
            e.Handled = true;
            MessageBeep(0);
        }
    }
}


来源:https://stackoverflow.com/questions/53680535/textbox-validate-input-before-paste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!