C# winfrom textbox 对于右键粘贴…

最近在做项目中遇到这样一个问题,用户希望在输入框中对右键粘贴和复制等功能进行有选择行的控制。之前我对于右键粘贴的控制就是监控系统粘贴板的内容,然后和正则表达式进行校验,如果不通过则清空textbox和粘贴板,但是这样不合理,下面说说我选择的做法:

禁用textbox里右键菜单的做法:

    textBox.ShortcutsEnabled = false;

我只是做了对粘贴的控制,对于剪切和复制等都有对于的消息码,可以做不同的操作。

这个方法必须放在继承自textbox的类 A 里面,然后在界面上用的textbox控件须是 A 实例化后的。

 protected override void WndProc(ref   Message m)
        {
            const int WM_CLEAR = 0x0303;
            const int WM_UNDO = 0x0304;
            const int WM_COPY = 0x0301;
            const int WM_CUT = 0x0300;
            const int WM_PASTE = 0x0302;

            switch (m.Msg)
            {
                case WM_CLEAR:
                    this.Text = "WM_CLEAR ";
                    break;
                case WM_COPY:
                    this.Text = "WM_COPY ";
                    break;
                case WM_CUT:
                    this.Text = "WM_CUT ";
                    break;
                case WM_UNDO:
                    this.Text = "WM_UNDO ";
                    break;
                case WM_PASTE:                   
                    if (ValueType != null && ValueType != "")

                     // ValueType:正则表达式字符串 
                    {
                        try
                        {
                            Regex objAlphaPatt;
                            objAlphaPatt = new Regex(ValueType);
                            string temp = "";
                            if (Clipboard.GetText().Length > 0)
                            {
                                temp = Clipboard.GetText();
                                if (!objAlphaPatt.IsMatch(temp))
                                    Flag = false;   //设置标志 外面做控制
                            }
                        }
                        catch (Exception e1)
                        {
                         Business.addLog("输入控件判断粘贴异常:" + e1, 1, 0);
                        }
                    }
                    break;              
                default:
                    break;
            }
            base.WndProc(ref   m);
        }

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页