在 main() 中为 SerialPort 添加事件处理程序
我尝试将事件处理程序订阅到数据接收事件。似乎我无法指定事件处理函数名称。我不明白为什么
myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
给我错误消息。
问题就到这里了,希望大家能够解答。
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);
}
}
}
}
I try to subscribe a event handler to the data received event. Seems like I cant specify the event handler function name. I dont understand why
myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
is giving me error message.
Here is the problem, hope anyone can answer it.
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);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,由于方法
Main
是静态的,因此您只能调用同一类中的其他静态方法。事实上,comPort_DataReceived
被声明为实例方法,以下代码应该修复事件处理程序的分配:其次,由于
myComPort
是在Main< 中定义的。 /code>,它在
comPort_DataReceived
中不可见。您有两种选择:要么将myComPort
声明为类的静态成员,要么使用事件处理程序的sender
参数:First, since method
Main
is static, you can only call other static methods in the same class. As it is,comPort_DataReceived
is declared as an instance method, the following code should fix the assignment of the event handler:Second, since
myComPort
is defined inMain
, it will not be visible incomPort_DataReceived
. You have two choices: either declaremyComPort
as a static member of your class, or use thesender
argument of the event handler:在您的事件处理程序中,myComPort 不在范围内 - 它是在您的 main() 方法中本地声明的。我建议您将 com 端口处理提取到一个类中,并使 myComPort 成为该类的成员变量。
另外,您的评论指出 SerialPort 类有一个托管资源,需要使用 IDisposable / using 模式来处理该资源,但您没有使用块来包装对通信端口的访问。
最后,您添加为事件处理程序的方法作为实例成员而不是静态成员存在;要从 main() 方法的静态范围访问它,您需要从类的实例中获取它或使该方法静态。
In your event handler, myComPort isn't in scope - it's declared locally in your main() method. I would suggest that you extract the com port handling into a class and make myComPort a member variable of that class.
Also, your comments note that the SerialPort class has a managed resource that it needs to dispose of using the IDisposable / Using pattern, but you don't have a using block wrapping the access to the comm port.
Last, the method you are adding as the event handler exists as an instance member rather than as a static member; to access it from the main() method's static scope, you need to either grab it from an instance of the class or make the method static.
Tetsujin no Oni 的答案是处理范围问题的理想方法。另一种可行的方法是将
myComPort
声明为程序的静态成员,例如:然后只需从
main
方法中删除myComPort
声明即可。Tetsujin no Oni's answer is the ideal way to handle your issue with scope. Another approach that also works is to declare
myComPort
as a static member of your Program, e.g.:Then simply remove the
myComPort
declaration from yourmain
method.