Wednesday 4 May 2016

How to clear clipboard text using C#.Net

Known exceptions:

Case 1:
It you use Clipboard.SetText(string.Empty) to clear clipboard text, you will get an ArgumentNullException exception: "Value cannot be NULL".

It is because you cannot set empty string or null using Clipboard.SetText function.

Case 2:
If you use Clipboard.Clear() function, you will get the below error:

"An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll

Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

To fix the above 2 exceptions, use the following code:

 public void deleteClipboardText()
        {
            try
            {
                Thread th = new Thread(new ThreadStart(clearClipboardText));
                th.SetApartmentState(ApartmentState.STA);
                th.Start();
                th.Join();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void clearClipboardText()
        {
            System.Windows.Forms.Clipboard.Clear();
        }