Search code examples
winformslistboxcopy-paste

System.Threading.ThreadStateException; Using Clipbord.setText/setDataObject crashes form


So I have a listbox that will be listing off several items, which looks like this: (https://i.sstatic.net/ualLr.jpg)

Shortly explained, I want to be able to select one of these items, and then when I ctrl + c, it would copy only the numbers in the item, using this code to seperate the numbers from the text:

string SelectedItemString = CLBSelectToDelete.SelectedItem.ToString(); //e.g "Offset at:(3453) from exampleFile.osu

string[] temp = SelectedItemString.Split('('); // for getting "3453) from exampleFile.osu"
string[] temp2 = temp[1].Split(')'); // for getting 3453
string StringToCopy = temp2[0]; //the 3453

Clipboard.SetText(StringToCopy); // or Clipboard.SetDataObject(StringToCopy); //for copying into  cliptray

The code seems to run fine until it attempts to copy the string into the clip tray, where it thows an exception:"System.Threading.ThreadStateException".

'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.'

Some extra info:

  • This is on a childform, using form.showDialogue();
  • This is triggered under the KeyDown event

I hope this is comprehensible, thanks in advance!


Solution

  • It turns out, you can't use OLE functions (Windows' build in functions like copy paste) when you are inside a thread/task. The solution of this problem has been resolved in this thread: C# WinForms: How to set Main function STAThreadAttribute