在 main() 中为 SerialPort 添加事件处理程序

发布于 2024-12-29 02:27:50 字数 2819 浏览 2 评论 0原文

我尝试将事件处理程序订阅到数据接收事件。似乎我无法指定事件处理函数名称。我不明白为什么

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

债姬 2025-01-05 02:27:50

首先,由于方法 Main 是静态的,因此您只能调用同一类中的其他静态方法。事实上,comPort_DataReceived 被声明为实例方法,以下代码应该修复事件处理程序的分配:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   // ...
}

其次,由于 myComPort 是在 Main< 中定义的。 /code>,它在 comPort_DataReceived 中不可见。您有两种选择:要么将 myComPort 声明为类的静态成员,要么使用事件处理程序的 sender 参数:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)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:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   // ...
}

Second, since myComPort is defined in Main, it will not be visible in comPort_DataReceived. You have two choices: either declare myComPort as a static member of your class, or use the sender argument of the event handler:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    // ...
}
绝不服输 2025-01-05 02:27:50

在您的事件处理程序中,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.

记忆消瘦 2025-01-05 02:27:50

Tetsujin no Oni 的答案是处理范围问题的理想方法。另一种可行的方法是将 myComPort 声明为程序的静态成员,例如:

internal List<Byte> portBuffer = new List<Byte>(1024);
private SerialPort myComPort = new SerialPort();

然后只需从 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.:

internal List<Byte> portBuffer = new List<Byte>(1024);
private SerialPort myComPort = new SerialPort();

Then simply remove the myComPort declaration from your main method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文