效果

代码
public partial class Form1 : Form
{
private AdsClient PLC_Client = new AdsClient();
private string AmsNetId = "39.64.16.138.1.1";
public Form1()
{
InitializeComponent();
}
private void bntConnect_Click(object sender, EventArgs e)
{
Task.Run(readtc2plc);
}
private void readtc2plc()
{
while (true)
{
try
{
if (PLC_Client.IsConnected)//读取PLC
{
btnConnect.BackColor = Color.Green;
uint handle = PLC_Client.CreateVariableHandle(".topc");
// 写入布尔值到PLC
//PLC_Client.WriteAny(handle, true);
// 读取布尔值从PLC
bool value = (bool)PLC_Client.ReadAny(handle, typeof(bool));
this.Invoke(new Action(() => { this.richTextBox1.Text += ".topc" + "=" + value + "\r\n"; }));
// 删除变量句柄
PLC_Client.DeleteVariableHandle(handle);
}
else//连接PLC
{
btnConnect.BackColor = Color.Red;
PLC_Client.Connect(AmsNetId, 801);
}
}
catch (Exception Err)
{
btnConnect.BackColor = Color.Red;
}
Thread.Sleep(1000);
}
}
private void closeBtn_Click(object sender, EventArgs e)
{
try
{
// 断开连接并释放资源
PLC_Client.Dispose();
// Task.Run(readtc2plc);
;
}
catch (Exception Err)
{
// ResultBox.Text += Err.Message + '\n';
}
}
}