using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using OPCAutomation;using ;namespace Opc_Client{public partial class Form1 : Form{public Form1(){InitializeComponent();}#region私?有®D变À?量¢?OPCServer SyServer;OPCGroups SyGroups;OPCGroup SyGroup;OPCItems SyItems;OPCItem SyItem;string strHostIP = string.Empty;string strHostName = string.Empty;bool opc_connected = false; //连¢?接¨®状Á¡ä态¬?int itmHandleClient = 0; //客¨ª户¡ì端?句?柄À¨²int itmHandleServer = 0; //服¤t务?端?句?柄À¨²#endregion#region方¤?法¤¡§private void GetLocalServer(){IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());if (IPHost.AddressList.Length > 0){strHostIP = IPHost.AddressList[4].ToString();this.tboxServerIP.Text = strHostIP.ToString();}else{return;}IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);strHostName = ipHostEntry.HostName.ToString();try{SyServer = new OPCServer();object serverList = SyServer.GetOPCServers(strHostName);foreach (string turn in (Array)serverList){this.cmbServerName.Items.Add(turn);cmbServerName.SelectedIndex = 0;btnConnServer.Enabled = true;}}catch (Exception err){MessageBox.Show("枚?举¨´本À?地Ì?OPC服¤t务?器¡Â出?错䨪:êo"+err.Message,"提¬¨¢示º?信?息¡é",MessageBoxButtons.OK,MessageBoxIcon.Warning);}}private bool CreatGroup(){try{SyGroups = SyServer.OPCGroups;SyGroup = SyGroups.Add("OPCDOTNETGROUP");SetGroupProperty();SyGroup.DataChange += newDIOPCGroupEvent_DataChangeEventHandler(SyGroup_DataChange);SyGroup.AsyncWriteComplete += newDIOPCGroupEvent_AsyncWriteCompleteEventHandler(SyGroup_AsyncWriteComplete);SyItems = SyGroup.OPCItems;}catch (Exception err){MessageBox.Show("创ä¡ä建¡§组Á¨¦出?现?错䨪误¨®"+err.Message,"提¬¨¢示º?信?息¡é",MessageBoxButtons.OK,MessageBoxIcon.Warning);return false;}return true;}private void LoadDataToTree(OPCBrowser oPCBrowser, TreeNodeCollection treeNodeCollection){anization.ToString();oPCBrowser.ShowBranches();foreach (object turn in oPCBrowser){TreeNode node = treeNodeCollection.Add(turn.ToString());treeView1.SelectedNode = node;oPCBrowser.MoveDown(turn.ToString());LoadDataToTree(oPCBrowser, node.Nodes);oPCBrowser.MoveUp();}oPCBrowser.ShowLeafs(false);foreach (object turn in oPCBrowser){treeView1.SelectedNode.Nodes.Add(turn.ToString());}}private void RecurBrows(OPCBrowser oPCBrowser){//string i = anizationLoadDataToTree(oPCBrowser, treeView1.Nodes[0].Nodes);oPCBrowser.ShowBranches();oPCBrowser.ShowLeafs(true);foreach (object turn in oPCBrowser){listBox1.Items.Add(turn.ToString());}}private void GetServerInfo(){this.toolStripStatusLabel1.Text = "开a始º?时º¡À间?:êo" + SyServer.StartTime.ToString() + " ";this.toolStripStatusLabel2.Text = "版ã?本À?:êo" +SyServer.MajorVersion.ToString() + "." + SyServer.MinorVersion.ToString() + "." + SyServer.BuildNumber.ToString();}private Boolean ConnectRemoteServer(string remoteServerIP, string remoteServerName){try{SyServer.Connect( remoteServerName,remoteServerIP);if (SyServer.ServerState == (int)OPCServerState.OPCRunning) {this.toolStripStatusLabel3.Text = "已°?连¢?接¨®到Ì?-" + SyServer.ServerName + " ";}else{this.toolStripStatusLabel3.Text = "状Á¡ä态¬?:êo" + SyServer.ServerState.ToString() + " ";}}catch (Exception err)MessageBox.Show("连¢?接¨®远?程¨¬服¤t务?器¡Â出?错䨪:êo" +err.Message, "提¬¨¢示º?信?息¡é", MessageBoxButtons.OK, MessageBoxIcon.Warning);return false;}return true;}private void SetGroupProperty(){SyServer.OPCGroups.DefaultGroupIsActive =Convert.ToBoolean(boBox1.SelectedItem);SyServer.OPCGroups.DefaultGroupDeadband = Convert.ToInt32(textBox1.Text); SyGroup.UpdateRate = Convert.ToInt32(textBox2.Text);SyGroup.IsActive = Convert.ToBoolean(comboBox2.SelectedItem);SyGroup.IsSubscribed = Convert.ToBoolean(comboBox3.SelectedItem);}#endregion#region事º?件tvoid SyGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors){this.lblState.Text = "";for (int i = 1; i <= NumItems; i++){this.lblState.Text += "Tran:êo" + TransactionID.ToString() + " CH:êo" + ClientHandles.GetValue(i).ToString() + " Error:êo" +Errors.GetValue(i).ToString();}}void SyGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps){for (int i = 1; i <= NumItems; i++){this.tboxcurrvalue.Text = ItemValues.GetValue(i).ToString();this.tboxcurrquality.Text = Qualities.GetValue(i).ToString();this.tboxcurrtime.Text = TimeStamps.GetValue(i).ToString();}}private void Form1_Load(object sender, EventArgs e){btnConnServer.Enabled = false;btnServerBrush.Enabled = false;btnsetproparty.Enabled = false;btnwritevalue.Enabled = false;treeView1.Nodes.Add("Root");GetLocalServer();//SyServer.OPCGroups.DefaultGroupIsActive =Convert.ToBoolean(boBox1.SelectedItem);}private void listBox1_SelectedIndexChanged(object sender, EventArgs e){try{if (itmHandleClient != 0){this.tboxcurrvalue.Text = "";this.tboxcurrquality.Text = "";this.tboxcurrtime.Text = "";Array Errors;OPCItem bItem = SyItems.GetOPCItem(itmHandleServer);int[] temp = new int[2] { 0, bItem.ServerHandle };Array serverHandle = (Array)temp;SyItems.Remove(SyItems.Count, ref serverHandle, out Errors);}//int cancelID;itmHandleClient = 1234;SyItem = SyItems.AddItem(listBox1.SelectedItem.ToString(), itmHandleClient);itmHandleServer = SyItem.ServerHandle;//SyItem.Read(listBox1.SelectedItem.ToString(), out Value, out Quality, out TimeStamp);//SyGroup.AsyncRead(1, ref serverHandle, out Errors, 2016, out cancelID); }catch (Exception err){itmHandleClient = 0;this.tboxcurrvalue.Text = "Error ox";this.tboxcurrquality.Text = "Error ox";this.tboxcurrtime.Text = "Error ox";MessageBox.Show("此ä?项?为a系¦Ì统ª3保À¡ê留¢?项?:êo"+err.Message,"提¬¨¢示º?信?息¡é");}}private void Form1_FormClosing(object sender, FormClosingEventArgs e){if (!opc_connected){return;}if (SyGroup != null){SyGroup.DataChange -=newDIOPCGroupEvent_DataChangeEventHandler(SyGroup_DataChange);}if (SyServer != null){SyServer.Disconnect();SyServer = null;}opc_connected = false;}private void btnsetproparty_Click(object sender, EventArgs e){SetGroupProperty();}private void btnConnServer_Click(object sender, EventArgs e){try{if (!ConnectRemoteServer(tboxServerIP.Text, cmbServerName.Text)){return;}btnsetproparty.Enabled = true;opc_connected = true;GetServerInfo();RecurBrows(SyServer.CreateBrowser());if (!CreatGroup()){return;}}catch (Exception err){MessageBox.Show("初?始º?化¡¥出?错䨪:êo"+err.Message,"提¬¨¢示º?信?息¡é",MessageBoxButtons.OK,MessageBoxIcon.Warning);}}private void btnwritevalue_Click(object sender, EventArgs e){OPCItem bItem = SyItems.GetOPCItem(itmHandleServer);int[] temp = new int[2] {0,bItem.ServerHandle };Array serverHandle = (Array)temp;object[] valueTemp = new object[2] { "", tboxvaluewrite.Text };Array values = (Array)valueTemp;Array Errors;int cancelID;SyGroup.AsyncWrite(1, ref serverHandle, ref values, out Errors, 2016, out cancelID);//SyItem.Write(tboxvaluewrite.Text);GC.Collect();}private void btnServerBrush_Click(object sender, EventArgs e){strHostIP = tboxServerIP.Text;cmbServerName.Items.Clear();IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);strHostName = ipHostEntry.HostName.ToString();try{SyServer = new OPCServer();object serverList = SyServer.GetOPCServers(strHostName);foreach (string turn in (Array)serverList){this.cmbServerName.Items.Add(turn);cmbServerName.SelectedIndex = 0;btnConnServer.Enabled = true;}}catch (Exception err){MessageBox.Show("枚?举¨´本À?地Ì?OPC服¤t务?器¡Â出?错䨪:êo" + err.Message, "提¬¨¢示º?信?息¡é", MessageBoxButtons.OK, MessageBoxIcon.Warning);}}}}。