#947 – Intercepting Paste Operations in a TextBox

Because the TextBox control automatically supports copy/cut/paste functionality, you may want to intercept paste events to determine if the text to be pasted should be allowed.

You can intercept data being pasted into a TextBox using a pasting handler.  Within the body of the handler, you check the text to be pasted and optionally cancel the paste operation if the text should not be allowed.

You call DataObject.AddPastingHandler when your application starts, specifying the TextBox for which you want to intercept paste events.

        public MainWindow()
        {
            this.InitializeComponent();
            DataObject.AddPastingHandler(txtMyText, PasteHandler);
        }

In the pasting handler, you call the CancelCommand method to reject paste operations.

        private void PasteHandler(object sender, DataObjectPastingEventArgs e)
        {
            TextBox tb = sender as TextBox;
            bool textOK = false;

            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                string pasteText = e.DataObject.GetData(typeof(string)) as string;
                Regex r = new Regex(@"^[a-zA-Z]+$");
                if (r.IsMatch(pasteText))
                    textOK = true;
            }

            if (!textOK)
                e.CancelCommand();
        }