Milad Milad - 13 days ago 6
C# Question

How to use Clipboard.GetText using a Task?

I'm programming a Windows form application which automates an old software. For transferring information between that software and my application I use Clipboard. Clicking a button on old software puts some information in the clipboard.

For using Clipboard.GetText I should call it from a windows form. But I don't want everything on UI thread.

When calling Clipboard.GetText in another task I got it says you should call Clipboard.GetText from an STAThread.

Answer

Your UI thread is a STA. But that doesn't mean you have to execute all your logic in the UI thread. You can execute all lines except the UI line in the background. That is possible by marshalling your Clipboard.GetText call back to the UI thread from your worker thrad (assuming you have a Form or any other Controlavailable - here in the ctrlvariable):

//Do something
Func<string> getClipboardText = delegate() { return Clipboard.GetText(); };
string clipboardText = (string)ctrl.Invoke(getClipboardText);
//Do something else