程序员的知识教程库

网站首页 > 教程分享 正文

C# .NET RichTextBox 如何控制只允许粘贴文本内容

henian88 2024-08-16 17:26:03 教程分享 5 ℃ 0 评论
    public class WenRichTextBox : RichTextBox
    {
        public WenRichTextBox() : base()
        {
        }

        public new bool ReadOnly
        {
            get => base.ReadOnly; set
            {
                base.ReadOnly = value;
                if (!value)
                    this.BackColor = Color.White;
                else
                    this.BackColor = SystemColors.Control;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.Control && e.KeyCode == Keys.V)
            {
                e.SuppressKeyPress = true;
                this.Paste(DataFormats.GetFormat(DataFormats.Text));
            }
        }
    }


RichTextBox ReadOnly 设置不允许输入后,颜色并没有和TextBox一样发生颜色变化,所以可以集成一个颜色变化功能。

避免粘贴 非文本内容,主要是控制 Ctrl - V 快捷键。直接重写 keyDown事件,

this.Paste(DataFormats.GetFormat(DataFormats.Text));

直接用这行代码即可解决。

然后可以封装成一个控件。后续直接直接调用。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表