My clipboard is populated with text, but when I run
string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);
I get back an empty string. I've toyed with various forms of the call including:
string clipboardData = Clipboard.GetText(); string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.UnicodeText);
But with the same result.
Am I missing something obvious?
You can only access the clipboard from an STA thread. Rick Brewster ran into this with some refactoring of the regular Edit->Paste command, in Paint.NET.
Code:
IDataObject idat = null; Exception threadEx = null; Thread staThread = new Thread( delegate () { try { idat = Clipboard.GetDataObject(); } catch (Exception ex) { threadEx = ex; } }); staThread.SetApartmentState(ApartmentState.STA); staThread.Start(); staThread.Join(); // at this point either you have clipboard data or an exception
Code is from Rick. http://forums.getpaint.net/index.php?/topic/13712-/page__view__findpost__p__226140
Update: Jason Heine made a good point of adding ()
after delegate
to fix the ambiguous method error.
Honestly, I don't know what a STA thread is, but in simple projects it might solve the problem to add [STAThread]
right before the Main
method:
[STAThread] static void Main(string[] args) { (...)
It works for me, so I don't question the method ;)
Further information about the [STAThread]
decorator is on blog post Why is STAThread required?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With