using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Windows.Forms; using AxActUtlTypeLib; public static class Copy { private static Dictionary plcDic = new Dictionary(); private static Form form = new Form(); // 创建一个隐藏的窗体 static Copy() { // 确保窗体已创建并运行消息泵 var thread = new Thread(() => Application.Run(form)); thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA thread.Start(); } public static int GetDevice(string ip, string szDeviceName) { int result = -1; var thread = new Thread(() => { try { if (plcDic.ContainsKey(ip)) { plcDic[ip].Open(); int deviceValue; var iReturnCode = plcDic[ip].GetDevice(szDeviceName, out deviceValue); if (iReturnCode == 0) { result = deviceValue; } else { plcDic[ip].Close(); plcDic[ip].Open(); } } } catch (Exception ex) { Console.WriteLine("Error in STA thread: " + ex.Message); } }); thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA thread.Start(); thread.Join(); // 等待线程完成 return result; } public static bool SetDevice(string ip, string szDeviceName, int arrDeviceValue) { bool result = false; var thread = new Thread(() => { try { if (plcDic.ContainsKey(ip)) { plcDic[ip].Open(); var iReturnCode = plcDic[ip].SetDevice(szDeviceName, arrDeviceValue); if (iReturnCode == 0) { result = true; } else { plcDic[ip].Close(); plcDic[ip].Open(); } } } catch (Exception ex) { Console.WriteLine("Error in STA thread: " + ex.Message); } }); thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA thread.Start(); thread.Join(); // 等待线程完成 return result; } private static void Init(string ip) { var thread = new Thread(() => { try { if (!plcDic.ContainsKey(ip)) { var axActUtlType = new AxActUtlType(); ((ISupportInitialize)axActUtlType).BeginInit(); form.Controls.Add(axActUtlType); // 将控件添加到窗体中 ((ISupportInitialize)axActUtlType).EndInit(); axActUtlType.ActLogicalStationNumber = 1; // 设置逻辑站号 var res = axActUtlType.Open(); if (res == 0) { plcDic.Add(ip, axActUtlType); } } } catch (Exception ex) { Console.WriteLine("Error in STA thread: " + ex.Message); } }); thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA thread.Start(); thread.Join(); // 等待线程完成 } }