在Wince和Windows Mobile下,很多設備以串口(Serial Port/Com Port)的方式提供訪問接口,例如 可以通過串口訪問GPS的receiver,從而接收NMEA Data。
在CF.NET2.0開始,MS把串口操作封裝了到System.IO.Ports.SerialPort裡面,大大簡便了對串口的操 作,不再需要P/Invoke就可以直接操作串口。
下面展現兩個串口通信類,一個負責發生,一個負責接收,兩個類分別在不要的設備上運行。
public class ReceiverPort : IDisposable
{
private readonly System.IO.Ports.SerialPort serialPort;
public ReceiverPort()
{
serialPort = new System.IO.Ports.SerialPort("COM1", 4800,
System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
serialPort.Handshake = System.IO.Ports.Handshake.None;
try
{
serialPort.DataReceived += new
System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort_DataReceived);
serialPort.Open();
if (serialPort.IsOpen)
{
Console.WriteLine("Open the serial port successful");
}
else
{
Console.WriteLine("Fail to open the serial port");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void Dispose()
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Dispose();
}
private void serialPort_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
Console.WriteLine("RECEIVED:" + serialPort.ReadLine());
}
}
public class SenderPort : IDisposable
{
private readonly System.IO.Ports.SerialPort serialPort;
public SenderPort()
{
serialPort = new System.IO.Ports.SerialPort("COM1", 4800,
System.IO.Ports.Parity.None, 8,
System.IO.Ports.StopBits.One);
serialPort.Handshake = System.IO.Ports.Handshake.None;
try
{
serialPort.Open();
if (serialPort.IsOpen)
{
Console.WriteLine("Open the serial port successful");
}
else
{
Console.WriteLine("Fail to open the serial port");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void Dispose()
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Dispose();
}
public bool Send(string str)
{
try
{
if (serialPort.IsOpen)
{
Console.WriteLine("SENT:" + str);
serialPort.WriteLine(str + "\r");
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}