Link to home
Create AccountLog in
Avatar of sfarley
sfarley

asked on

Getting data from the clipboard

I recently upgraded my application from Visual Studio 2003 to Visual Studio 2005. I had a form within my application that would take the highlighted text from the previous form and copy it into the rich text box. The code was basically this:
IDataObject clipboardData = Clipboard.GetDataObject();
tbxInput.AppendText(clipboardData.GetData(DataFormats.UnicodeText).ToString());

tbxInput is the RichTextBox that I am trying to paste the text from the previous form. This used to work if the user either highlighted the desired text or highlights and used Ctrl-C. Now, Clipboard.GetDataObject is returning null since I upgraded to Visual Studio 2005. Any ideas?
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Have you tried:

string text = System.Windows.Forms.Clipboard.GetText();
tbxInput.AppendText(text);
Avatar of sfarley
sfarley

ASKER

text is empty when I do that. It is strange since this code used to work and the only difference in this portion is the fact that I used to use VS 2003 and am now using VS 2005. If I use Ctrl-C on the first form and then Ctrl-V to copy it to the second for, it works fine. I saw something regarding needing to set the CurrentThread.ApartmentState  to STA. In the current application, this is not set.  Have you had to do this?

Thank you,
Susan
Avatar of sfarley

ASKER

I might have found something: http://channel9.msdn.com/ShowPost.aspx?PostID=13831
"The .NET documentation for Clipboard says that all public static members of it are thread-safe. Unfortunately, this is not true, at least in the .NET 2.0 beta. If you call Clipboard.GetDataObject or Clipboard.SetDataObject from a thread other than your WinForms application's main thread, they won't do anything (GetDataObject will return null, and SetDataObject will be a no-op.) Same with all the other methods of Clipboard that I tried."

Anyone know a workaround?
SOLUTION
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of sfarley

ASKER

I think something else may be going on. On the new form, I have a button that will copy the results for the user and uses the Clipboard.SetDataObject (tbxOutput.Text.Trim());
and I get the following error:
"Current thread must be set to a single thread apparment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."
I checked my Main, and I do have:
[STAThread]
static void Main()
I get null from the Clipboard even when I try to GetText() or GetDataObject() from the Main form. Any ideas?

Thank you,
Susan
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account