System.Threading.ThreadStateException;使用 Clipbord.setText/setDataObject 会导致表单崩溃
System.Threading.ThreadStateException; Using Clipbord.setText/setDataObject crashes form
所以我有一个列表框,它将列出几个项目,如下所示:
(https://imgur.com/a/EzUE2QL)
简短说明,我希望能够 select 这些项目之一,然后当我 ctrl + c 时,它只会复制项目中的数字,使用此代码将数字与正文:
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
代码似乎 运行 正常,直到它尝试将字符串复制到剪辑托盘中,然后抛出异常:“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.'
一些额外信息:
- 这是一个子窗体,使用 form.showDialogue();
- 这是在KeyDown事件下触发的
我希望这是可以理解的,提前致谢!
事实证明,当您在 thread/task 中时,您不能使用 OLE 函数(Windows' 内置函数,如复制粘贴)。这个问题的解决方案已经在这个线程中得到解决:C# WinForms: How to set Main function STAThreadAttribute
所以我有一个列表框,它将列出几个项目,如下所示: (https://imgur.com/a/EzUE2QL)
简短说明,我希望能够 select 这些项目之一,然后当我 ctrl + c 时,它只会复制项目中的数字,使用此代码将数字与正文:
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
代码似乎 运行 正常,直到它尝试将字符串复制到剪辑托盘中,然后抛出异常:“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.'
一些额外信息:
- 这是一个子窗体,使用 form.showDialogue();
- 这是在KeyDown事件下触发的
我希望这是可以理解的,提前致谢!
事实证明,当您在 thread/task 中时,您不能使用 OLE 函数(Windows' 内置函数,如复制粘贴)。这个问题的解决方案已经在这个线程中得到解决:C# WinForms: How to set Main function STAThreadAttribute