如何检查剪贴板同样检查按键已经做了什么?

时间:2013-09-20 11:42:34

标签: c# clipboard keypress

我没有找到一个可以验证我正在粘贴的每个字符的事件。我需要使用ASCII代码验证'因为我想处理'和“

KeyPress事件:

private void txt_KeyPress(object sender, KeyPressEventArgs e)
{    
    if( e.KeyChar == 34 || e.KeyChar == 39)//34 = " 39 = '
    {
       e.Handled = true; 
    }

}

简单解决方案:

private void txt_TextChanged(object sender, EventArgs e)
    {
        string text = txt.Text;
        while (text.Contains("\"") || text.Contains("'")) text = text.Replace("\"", "").Replace("'", "");
        txt.Text = text;
    }

1 个答案:

答案 0 :(得分:0)

您可以使用Clipboard.GetText()访问剪贴板文本,您可以通过覆盖控件的WndProc并查看消息0x302(WM_PASTE)来截取低级别Windows消息。

namespace ClipboardTests
{
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        private MyCustomTextBox MyTextBox;
        public Form1()
        {
            InitializeComponent();
            MyTextBox = new MyCustomTextBox();
            this.Controls.Add(MyTextBox);
        }
    }

    public class MyCustomTextBox : TextBox
    {
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x302 && Clipboard.ContainsText())
            {
                var cbText = Clipboard.GetText(TextDataFormat.Text);
                // manipulate the text
                cbText = cbText.Replace("'", "").Replace("\"", "");
                // 'paste' it into your control.
                SelectedText = cbText;
            }
            else
            {
                base.WndProc(ref m);
            }
        }
    }
}