Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Winforms System.Threading.ThreadStateException;使用Clipbord.setText/setDataObject崩溃表单_Winforms_Listbox_Copy Paste - Fatal编程技术网

Winforms System.Threading.ThreadStateException;使用Clipbord.setText/setDataObject崩溃表单

Winforms System.Threading.ThreadStateException;使用Clipbord.setText/setDataObject崩溃表单,winforms,listbox,copy-paste,Winforms,Listbox,Copy Paste,我有一个列表框,它将列出几个项目,如下所示: () 简要说明,我希望能够选择其中一个项目,然后当我按住ctrl+c键时,它将仅复制项目中的数字,使用以下代码将数字与文本分开: string SelectedItemString = CLBSelectToDelete.SelectedItem.ToString(); //e.g "Offset at:(3453) from exampleFile.osu string[] temp = SelectedItemString.Split

我有一个列表框,它将列出几个项目,如下所示: ()

简要说明,我希望能够选择其中一个项目,然后当我按住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”

'在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式。确保主函数上标记了STAThreadAttribute。”

一些额外信息:

  • 这在子窗体上,使用form.showDialogue()
  • 这是在KeyDown事件下触发的

我希望这是可以理解的,提前谢谢

事实证明,当您在线程/任务中时,不能使用OLE函数(Windows的内置函数,如复制粘贴)。此问题的解决方案已在此线程中解决:

[STAThread]
通常应用于WinForms项目中Program.cs中的
Main()
。除了启动线程外,没有理由在其他任何地方设置它。是吗?不清楚这里有什么
s
。它不应该是
SelectedItemString
?您可以使用
Regex.Match(SelectedItemString,@“\d+”).Value
获取字符串的数字内容,因此对于“s”,它指的是StringToCopy,我忘了更改它以使其更易于理解。其次,使用
Regex.Match(SelectedItemString,@“\d+”).Value
将假定整个字符串不包含任何其他需要的数值,在这种情况下,这并不完全理想,因为我不想将其他数值保存到字符串中。
Regex.Match(input,@“\(\d+)”).Groups[1].Value
。您正在展示的代码不需要线程。这是一个更大的代码的一部分,它是一个线程,我只是想知道问题出在哪里,但我已经找到了解决方案。也谢谢你的代码,非常有用!