Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for clipboard text change (error)

I'm trying to detect every time the clipboard data changes. And so, I set a timer and have it continuously check Clipboard.GetText() for changes.

I'm using the following code:

public void WaitForNewClipboardData()
{
    //This is in WPF, Timer comes from System.Timers
    Timer timer = new Timer(100);
    timer.Elapsed += new ElapsedEventHandler(
        delegate(object a, ElapsedEventArgs b){
            if (Clipboard.GetText() != ClipBoardData)
            {
                SelectedText.Text = Clipboard.GetText();
                ClipBoardData = Clipboard.GetText();
                timer.Stop();
            }
        });
    timer.Start();
}

I get the following error when it runs:

Current thread must be set to singlethread apartment (STA) mode before OLE calls can be made.

Does anyone know why?

like image 969
mattsven Avatar asked Feb 25 '23 01:02

mattsven


1 Answers

Your method accesses the Clipboard class, which is an OLE call that needs the caller to be in STA mode. Most likely the issue here is with your timer, which operates on a different thread. Here is a link that will help you out with more information about this:

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/2411f889-8e30-4a6d-9e28-8a46e66c0fdb/

Also, here is a link to a full article on how to monitor the clipboard by tapping into the Windows events:

http://www.radsoftware.com.au/articles/clipboardmonitor.aspx

I think this article will give you some tips on how better to monitor the clipboard and thus you will avoid this issue. While it is still good to know why the error occurred, there is a better way for this task to be accomplished.

like image 137
IAmTimCorey Avatar answered Feb 26 '23 16:02

IAmTimCorey