usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;//引用Twincat.ads和Sustem.IO
usingTwinCAT.Ads;usingSystem.IO;namespacewriteread
{public partial classForm1 : Form
{publicForm1()
{
InitializeComponent();
}//定义所需变量
private bool writebool =false;private bool readbool=false;private short writeint = 0;private short readint = 0;private int writelong = 0;private int readlong = 0;private float writereal = 0;private float readreal = 0;private double writelreal = 0;private double readlreal = 0;private string writestring = "";private string readstring = "";private int stringlen = 0;//定义结构体类型
public structstructtype
{public bools1;public booldummy1;public booldummy2;public booldummy3;public shorts2 ;public shortdummy4;public ints3 ;public floats4;public doubles5 ;
}//实例化结构体
private structtype structtest =newstructtype ();//定义数组,含有五个元素
private short[] arraytest = new short[5];//定义句柄变量
private int hvar = new int();//通讯数据定义
private TcAdsClient tcclient;//定义通讯协议
private void Form1_Load(objectsender, EventArgs e)
{//通讯协议
tcclient = newTcAdsClient();//tcclient.Connect("控制器NetID",851)
tcclient.Connect(851);
}//writebool
private void button1_Click(objectsender, EventArgs e)
{if (writebool == true)
{
writebool= false;
}else{
writebool= true;
}try{
hvar= tcclient.CreateVariableHandle("MAIN.BoolTest");
tcclient.WriteAny(hvar ,writebool );
tcclient.DeleteVariableHandle(hvar);
}catch(Exception err)
{
}
}//readbool
private void button2_Click(objectsender, EventArgs e)
{try{
hvar= tcclient.CreateVariableHandle("MAIN.BoolTest");
readbool= (bool)(tcclient.ReadAny(hvar, typeof(bool)));
tcclient.DeleteVariableHandle(hvar);