.Net Com口通信编程例子

        private string _sComPortNumber;
private bool _bFoundPortNumber;
private System.Windows.Forms.Control _oStaticShow;
private System.IO.Ports.SerialPort _oCIMControler;

/// <summary>
/// COM口名
/// </summary>
public string ComPortName { get { return _sComPortNumber; } }
/// <summary>
/// 编码
/// </summary>
public Encoding StringEncoding { get; set; }
/// <summary>
/// 比特率
/// </summary>
public int BaudRate { get; set; }
/// <summary>
/// 数据位
/// </summary>
public int DataBits { get; set; }
/// <summary>
/// 奇偶检验
/// </summary>
public System.IO.Ports.Parity Parity { get; set; }
/// <summary>
/// 停止位
/// </summary>
public System.IO.Ports.StopBits StopBits { get; set; }

private bool OpenPortAndSendMsg()
{
foreach (string tmpName in System.IO.Ports.SerialPort.GetPortNames())
{
foreach (string sCurrentMachinePortNumber in System.IO.Ports.SerialPort.GetPortNames())
{
try
{
if (_bFoundPortNumber == false)
{
System.IO.Ports.SerialPort otmpsp
= new System.IO.Ports.SerialPort();
otmpsp.DataReceived
+= new System.IO.Ports.SerialDataReceivedEventHandler(otmpsp_DataReceived);
otmpsp.PortName
= sCurrentMachinePortNumber;
otmpsp.BaudRate
= this.BaudRate;
otmpsp.DataBits
= this.DataBits;
otmpsp.Parity
= this.Parity;
otmpsp.StopBits
= this.StopBits;
otmpsp.Open();

//写数据************************
otmpsp.Write(new byte[] { 2 }, 0, 1);
string Command = "ST";
otmpsp.Write(Command);
otmpsp.Write(
new byte[] { 3 }, 0, 1);
otmpsp.Write(
new byte[] { 6 }, 0, 1);
otmpsp.Write(
new byte[] { 5 }, 0, 1);
//****************************

System.Threading.Thread.Sleep(
500);

otmpsp.Close();
}
else
{
return true;
}
}
catch (Exception ex)
{
}
}
}
return false;
}

void otmpsp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
System.IO.Ports.SerialPort oSenderObject
= sender as System.IO.Ports.SerialPort;
if (oSenderObject.BytesToWrite > 0)
{
oSenderObject.BaseStream.Flush();
}
int iReadFlag = oSenderObject.BytesToRead;
while (iReadFlag > 0)
{
string sReturn = oSenderObject.ReadExisting();
if (sReturn.Contains(""))
{
_bFoundPortNumber
= true;
_sComPortNumber
= oSenderObject.PortName;
}
iReadFlag
= oSenderObject.BytesToRead;
}
}

你可能感兴趣的:(.net)