当前位置: 移动技术网 > IT编程>开发语言>c# > C#线程间不能调用剪切板的解决方法

C#线程间不能调用剪切板的解决方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

最近做一个c#项目,需要用到线程,而且要用到剪切板,创建了一个子线程之后发现在子线程中剪切板上获取不到数据,经过一番查找与测试最终该问题得以解决,现将解决方法归纳如下,供大家参考:

第一步:

public void btnautofocus_click(object sender,eventargs e)
{
thread mythread = new thread(msc.autofocusarithmetic);
//注意,一般启动一个线程的时候没有这句话,但是要操作剪切板的话这句话是必需要加上的,
//因为剪切板只能在单线程单元中访问
//这里的sta就是指单线程单元
mythread .setapartmentstate(apartmentstate.sta); 
mythread .start();
}

第二步:还需要将program启动类中

static class program
{
///
/// 应用程序的主入口点。
///

[stathread] //这句话保留,如果要在主线程中访问剪切板,这句式必须要的
//如果要在子线程中访问剪切板,这个应该可以不要,但是默认是有的
static void main()
{
application.enablevisualstyles();
application.setcompatibletextrenderingdefault(false);
application.run(new mainform());
//application.run(new testrgbpixelthumbform());
//application.run(new testimageform());
//application.run(new testjudgedefinitionform());
//application.run(new testvirusform());
}
}

第三步:这个是读取剪切板数据

private image getcaptureimage()
{
idataobject idata = clipboard.getdataobject();
image img = null;
if (idata != null)
{
if (idata.getdatapresent(dataformats.bitmap))
{
img = (image)idata.getdata(dataformats.bitmap);
}
else if (idata.getdatapresent(dataformats.dib))
{
img = (image)idata.getdata(dataformats.dib);
}
}
return img;
}

至此问题得以解决。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网