Я пытаюсь подписать обработчик событий на событие полученных данных.Похоже, я не могу указать имя функции обработчика событий.Я не понимаю, почему
myComPort.DataReceived + = new SerialDataReceivedEventHandler (comPort_DataReceived);дает мне сообщение об ошибке.Вот проблема, надеюсь, кто-нибудь может ответить на нее.
занятый кот http://img827.imageshack.us/img827/5904/20120125102247.png
занятый кот http://img444.imageshack.us/img444/3855/20120125102202.png
namespace serialport
{
public class Program
{
internal List<Byte> portBuffer = new List<Byte>(1024);
static void Main()
{
//1. find available COM port
string[] nameArray = null;
string myComPortName = null;
nameArray = SerialPort.GetPortNames();
if (nameArray.GetUpperBound(0) >= 0)
{
myComPortName = nameArray[0];
}
else
{
Console.WriteLine("Error");
return;
}
//2. create a serialport object
// the port object is closed automatically by use using()
SerialPort myComPort = new SerialPort();
myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
myComPort.PortName = myComPortName;
//the default paramit are 9600,no parity,one stop bit, and no flow control
//3.open the port
try
{
myComPort.Open();
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
//Add timeout, p161
//reading Bytes
byte[] byteBuffer = new byte[10];
Int32 count;
Int32 numberOfReceivedBytes;
myComPort.Read(byteBuffer, 0, 9);
for (count = 0; count <= 3; count++)
{
Console.WriteLine(byteBuffer[count].ToString());
}
}
//The event handler should be static??
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int numberOfBytesToRead;
numberOfBytesToRead = myComPort.BytesToRead;
byte[] newReceivedData = new byte[numberOfBytesToRead];
myComPort.Read(newReceivedData, 0, numberOfBytesToRead);
portBuffer.AddRange(newReceivedData);
ProcessData();
}
private void ProcessData()
{
//when 8 bytes have arrived, display then and remove them from the buffer
int count;
int numberOfBytesToRead = 8;
if (portBuffer.Count >= numberOfBytesToRead)
{
for (count = 0; count < numberOfBytesToRead; count++)
{
Console.WriteLine((char)(portBuffer[count]));
}
portBuffer.RemoveRange(0, numberOfBytesToRead);
}
}
}
}