本文介绍了添加主)事件处理程序(的SerialPort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试订阅一个事件处理程序接收到的事件的数据。好像我不能指定事件处理函数的名称。我不明白为什么结果
myComPort.DataReceived + =新SerialDataReceivedEventHandler(comPort_DataReceived);是给我的错误信息。
这是问题所在,希望任何人都可以回答这个问题。





 命名空间的SerialPort 
{
公共类节目
{

内部列表<&字节GT; portBuffer =新的List<&字节GT;(1024);

静态无效的主要()
{


// 1。找到可用的COM端口
的String [] nameArray = NULL;
字符串myComPortName = NULL;
nameArray = SerialPort.GetPortNames();
如果(nameArray.GetUpperBound(0)> = 0)
{
myComPortName = nameArray [0];
}
,否则
{
Console.WriteLine(错误);
的回报;
}


// 2。创建一个对象的serialport
//端口对象是通过使用使用自动关闭()
的SerialPort myComPort =新的SerialPort();
myComPort.DataReceived + =新SerialDataReceivedEventHandler(comPort_DataReceived);
myComPort.PortName = myComPortName;
//默认paramit为9600,无奇偶校验,一个停止位,无流控制



//3.open港口
尝试
{
myComPort.Open();
}
赶上(UnauthorizedAccessException前)
{
MessageBox.Show(ex.Message);
}
//添加超时,P161

//读取字节
字节[] = ByteBuffer中新的字节[10];
的Int32计数;
的Int32 numberOfReceivedBytes;
myComPort.Read(ByteBuffer的,0,9);
为(计数= 0; COUNT< = 3;计数++)
{
Console.WriteLine(ByteBuffer的[统计]的ToString());
}


}
//事件处理程序应该是静态的?
无效comPort_DataReceived(对象发件人,SerialDataReceivedEventArgs E)
{
INT numberOfBytesToRead;
numberOfBytesToRead = myComPort.BytesToRead;
字节[] = newReceivedData新的字节[numberOfBytesToRead]
myComPort.Read(newReceivedData,0,numberOfBytesToRead);
portBuffer.AddRange(newReceivedData);
过程数据();
}
私人无效过程数据()
{
//当8个字节已经抵达,然后显示屏和缓冲区
INT删除它们计数;
INT numberOfBytesToRead = 8;

如果(portBuffer.Count> = numberOfBytesToRead)
{
为(计数= 0; COUNT< numberOfBytesToRead;计数++)
{
控制台.WriteLine((炭)(portBuffer [计数]));
}
portBuffer.RemoveRange(0,numberOfBytesToRead);
}
}

}

}


解决方案

在事件处理程序,myComPort是不在范围内 - 它在你的main()方法本地声明。我建议你抽取COM端口处理到一个类,使myComPort该类的成员变量。



另外,您的意见指出,SerialPort类具有管理资源,它需要配置使用了IDisposable /使用模式,但你没有使用块包裹访问通讯端口。



最后,该方法您要添加的事件处理程序中存在的一个实例成员,而不是作为一个静态成员;从main()方法的静态范围内访问它,你需要从这个类的一个实例,抓住它,或使该方法是静态的。


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);
            }
        }

    }

    }
解决方案

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.

这篇关于添加主)事件处理程序(的SerialPort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:19