4

I have a simple WPF app which creates a Thread, polls the clipboard every second and trims any strings it finds

However, in the background thread, once the string content changes, the clipboard methods fail with the exception

OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN))

Example: I have "ABC" on my clipboard and launch the app. A messagebox will popup with the string ABC. Now I copy a string "DEF" and instead of a message box popping up, the application crashes with the above error

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Thread t = new Thread(new ThreadStart(cleanStr));
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
        void cleanStr()
        {
            string prevStr = "";
            int err = 0;
            while (true)
            {
                    if (Clipboard.ContainsText() && !prevStr.Equals(Clipboard.GetText()))
                    {
                        prevStr = Clipboard.GetText();
                        prevStr=prevStr.Trim();
                        Clipboard.SetText(prevStr);
                        MessageBox.Show(prevStr);
                        Thread.Sleep(1000);
                    }
            }
        }
Akash
  • 1,716
  • 2
  • 23
  • 43
  • Why would you want to do this? – stuartd Jul 03 '15 at 20:11
  • @stuartd often I end up copying and pasting passwords, and trailing spaces get copied even though they shouldnt be in the password.. this seemed like an easy solution – Akash Jul 03 '15 at 20:15
  • 1
    First, remember strings are immutable, so you would have to do: "prevStr = prevStr.Trim()" to do the actual trimming of spaces. Secondly, instead of using a thread....look for clipboard change notification....and then update the clipboard when it has been detected.... http://stackoverflow.com/questions/2226920/how-to-monitor-clipboard-content-changes-in-c – Colin Smith Jul 03 '15 at 23:15
  • @ColinSmith ah. silly mistake about the string handling :) I'll try out the change notification method, but still, this simple thread based approach should also work right? I'm curious why it doesnt – Akash Jul 04 '15 at 06:34
  • It is a standard threading race bug. Modifying the clipboard content is not atomic, it is an open > write > close operation under the hood. You need a lock to ensure that your worker thread doesn't try to access the clipboard while the UI thread is busy putting text on it. Problem is, there isn't any practical way to change all the WPF code to use that lock as well. No point in trying to pursue this, it cannot work. – Hans Passant Jul 04 '15 at 09:36
  • @HansPassant Thanks, you're referring to the WPF UI thread right? It shouldnt be trying to put any data on the clipboard, since I havent written any code to do so. Or does it access the clipboard by default? – Akash Jul 04 '15 at 09:54

0 Answers0