#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();
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #947 – Intercepting Paste Operations in a TextBox

  1. Pingback: Dew Drop – November 11, 2013 (#1664) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: