0

So I have a listbox that will be listing off several items, which looks like this: (https://i.stack.imgur.com/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!

Himada
  • 1
  • 4
  • `[STAThread]` is usually applied to `Main()` in Program.cs in a WinForms Project. There's no reason to set it anywhere else except when you start a Thread. Did you? Not clear what `s` is here. Shouldn't it be `SelectedItemString`? You can get the numeric content of the string with `Regex.Match(SelectedItemString, @"\d+").Value` – Jimi Nov 07 '20 at 15:18
  • so as for the "s", it's referring to StringToCopy, which I forgot to change to make it more comprehensible. Secondly, using `Regex.Match(SelectedItemString, @"\d+").Value` would assume that the entire string will not contain any other numeric value then needed ones, in this case it's not exactly ideal since there will be other numeric values that I don't want to save to the string. – Himada Nov 09 '20 at 08:06
  • `Regex.Match(input, @"\((\d+)\)").Groups[1].Value`. The code you're showing doesn't require Threads. – Jimi Nov 09 '20 at 08:23
  • This is part of a bigger code that is a thread, I just wanted to know what was the problem, but I've found the solution. Also thanks for that code, very helpful! – Himada Nov 11 '20 at 12:21

1 Answers1

0

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

Himada
  • 1
  • 4