Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipboard.GetText returns null (empty string)

Tags:

c#

.net

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?

like image 778
Matthew Avatar asked Feb 06 '09 00:02

Matthew


2 Answers

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.

like image 83
BoltBait Avatar answered Sep 25 '22 03:09

BoltBait


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?.

like image 33
Danilo Bargen Avatar answered Sep 24 '22 03:09

Danilo Bargen