C# 通过网络和三菱的PLC通信
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PLCTest2
{
public partial class Form1 : Form
{
private AxActUtlTypeLib.AxActUtlType axActUtlType = null ;
public Form1()
{
InitializeComponent();
this .axActUtlType = new AxActUtlTypeLib.AxActUtlType();
//((System.ComponentModel.ISupportInitialize)(this.axActUtlType)).BeginInit();
this .Controls.Add( this .axActUtlType); //貌似这个控件必须要加到Controls中,不然就会引发异常。
}
private void btnConn_Click( object sender, EventArgs e)
{
try
{
int iStation = Convert.ToInt32( this .txtStationNo.Text.Trim());
this .axActUtlType.ActLogicalStationNumber = iStation;
this .axActUtlType.ActPassword = this .txtPassword.Text.Trim();
int rtn = this .axActUtlType.Open();
if (rtn == 0)
{
ShowMsg( "连接成功!" );
this .txtStationNo.Enabled = false ;
this .txtPassword.Enabled = false ;
this .btnConn.Enabled = false ;
}
else
{
ShowMsg( "连接失败" );
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
private void ShowMsg( string msg)
{
string str = string .Format(DateTime.Now.ToString( "HH:mm:ss" ) "_" msg);
this .richTextBox1.SelectionStart = this .richTextBox1.Text.Length;
this .richTextBox1.SelectedText = (str Environment.NewLine);
this .richTextBox1.ScrollToCaret();
}
private void btnRead_Click( object sender, EventArgs e)
{
try
{
string strAddr = this .txtAddr.Text.Trim();
int num = Convert.ToInt32( this .txtNum.Text.Trim());
short [] arr = new short [num];
int rtn = this .axActUtlType.ReadDeviceBlock2(strAddr, num, out arr[0]);
if (rtn == 0)
{
ShowMsg( "读取数据成功!" );
for ( int i = 0; i < arr.Length; i )
{
ShowMsg( string .Format( "{0:X4}" , arr[i]));
}
}
else
{
ShowMsg( "读取数据失败" );
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
private void btnWrite_Click( object sender, EventArgs e)
{
try
{
string strAddr = this .txtAddr.Text.Trim();
string [] strData = this .txtData.Lines;
int num = strData.Length;
short [] arr = new short [num];
for ( int i = 0; i < num; i )
{
arr[i] = Convert.ToInt16(strData[i]);
}
int rtn = this .axActUtlType.WriteDeviceBlock2(strAddr, num, ref arr[0]);
if (rtn == 0)
{
ShowMsg( "写入数据成功!" );
this .txtNum.Text = num.ToString();
}
else
{
ShowMsg( "写入数据失败" );
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
}
}
|
标签: C# 网络 c 通信 的