首先程序的入口处需要加上[STAThread]
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
发现之前的答案少写了ThreadStart的内容,时间太久了,这是我现在在用的,直接调用即可。
因为我不需要使用到除文字外的剪切板操作,故只有操作文字的代码,其他的如图片之类的剪切板操作仅供参考。
public class 操作剪切板文字
{
public string 获取剪切板的文字() {
string idat = null;
Exception threadEx = null;
Thread staThread = new Thread(
delegate () {
try {
idat = Clipboard.GetText(TextDataFormat.UnicodeText);
} catch (Exception ex) {
threadEx = ex;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
return idat;
}
public void 设置剪切板的文字(string ID) {
Exception threadEx = null;
Thread staThread = new Thread(
delegate () {
try {
Clipboard.SetText(ID);
} catch (Exception ex) {
threadEx = ex;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
}
}
------------------------------------------旧版答案,其中少写了ThreadStart内容----------------------------------
其次在调用的时候,要将剪切板的操作新建一个方法,再通过线程的方式调用他。
Thread t = new Thread(new ThreadStart(剪切板设置));
t.SetApartmentState(ApartmentState.STA);
t.Start();
private void 剪切板设置(string ID) {
Clipboard.SetData(DataFormats.Text, ID);//复制内容到剪切板
}