Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 388
Milad Avatar asked Dec 06 '25 19:12

Milad


1 Answers

You are going to have to alter your expectations. It is a standard requirement that only the UI thread interact with the clipboard.

Technically speaking, the actual requirement, as called out in the documentation, is that only single-threaded apartment (STA) threads can access the clipboard. Because most background threads, like those created by the ThreadPool class in .NET, are multi-threaded apartment (MTA) threads, they cannot access the clipboard. You can work around this by manually creating your own STA thread and running a message pump on it, but it is far easier to just use the UI thread, so that's what everyone does.

However, it is a poor design to begin with to try and use the clipboard to share information between two processes. The clipboard is intended for the user to store information. Anything you write to the clipboard will clobber whatever the user had stored there. If your application does this, and overwrites something that I wanted to keep, I'm going to be exceptionally furious with you.

There are better ways for processes to communicate with each other; search for "interprocess communication" (abbreviated "IPC") for various ideas.

like image 126
Cody Gray Avatar answered Dec 08 '25 11:12

Cody Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!