类中调用界面ActiveX控件报错当前线程不在单线程单元中因此无法实例化 ActiveX 控件的解决办法

时间:2022-09-08 17:58:13

解决办法是Form类中定义一个静态的ActiveX对象,在formload中将界面上的ActiveX对象赋值给新定义的对象,类中访问该静态对象即可.

public static AxClientDriver_NTLib.AxClientDriverCtrl com = new AxClientDriver_NTLib.AxClientDriverCtrl();

private void Form1_Load(object sender, EventArgs e)
{
com = this.axClientDriverCtrl1;
isRunning = true;

this.FormClosing += Form1_FormClosing;
Thread t = new Thread(StartServer);
////t.SetApartmentState(ApartmentState.STA);//关键设置
t.Start();

}

public class A

{

public void GetZhiWen()

{

//new AxClientDriver_NTLib.AxClientDriverCtrl().GWQ_SignFinger(); /*报错:

当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“f1b35062-91ea-47fd-a71e-872c114220b0”。System.Threading.ThreadStateException: 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“f1b35062-91ea-47fd-a71e-872c114220b0”。*/

Form1.com.GWQ_SignFinger();

}

}