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

2024-04-12

我尝试将事件处理程序订阅到数据接收事件。似乎我无法指定事件处理函数名称。我不明白为什么
myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);给我错误信息。 问题就到这里了,希望大家能够解答。

一只忙碌的猫 http://img827.imageshack.us/img827/5904/20120125102247.png http://img827.imageshack.us/img827/5904/20120125102247.png

一只忙碌的猫 http://img444.imageshack.us/img444/3855/20120125102202.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);
            }
        }

    }

    }

一、since方法Main是静态的,只能调用同一个类中的其他静态方法。事实上,comPort_DataReceived被声明为实例方法,以下代码应修复事件处理程序的分配:

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

第二,自从myComPort定义于Main,它将不可见于comPort_DataReceived。你有两个选择:要么声明myComPort作为类的静态成员,或者使用sender事件处理程序的参数:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 main() 中为 SerialPort 添加事件处理程序 的相关文章

  • WPF 中的屏幕分辨率问题?

    我将在 WPF 中使用以下代码检测分辨率 double height System Windows SystemParameters PrimaryScreenHeight double width System Windows Syste
  • 为什么存在 async 关键字

    浏览 msdn 9 频道视频时 我发现以下未答复的评论 希望有人能解释一下 我不明白 async 关键字的意义 为什么不直接允许 任何时候方法返回任务时都会使用await关键字 就像迭代器一样 可以在任何返回 IEnumerable 的方法
  • System.IO.IOException:由于意外>数据包格式,握手失败?

    有谁知道这意味着什么 System Net WebException 底层连接已关闭 发送时发生意外错误 gt System IO IOException 由于意外 握手失败 数据包格式 在 System Net Security SslS
  • ASP.NET Core 与现有的 IoC 容器和环境?

    我想运行ASP NET 核心网络堆栈以及MVC在已托管现有应用程序的 Windows 服务环境中 以便为其提供前端 该应用程序使用 Autofac 来处理 DI 问题 这很好 因为它已经有一个扩展Microsoft Extensions D
  • 为什么Apache MPM prefork.c 使用互斥体来保护accept()?

    我坐下来读书Apache 的 MPM prefork c http code metager de source xref apache httpd server mpm prefork prefork c这段代码使用了一个名为accept
  • 为什么大多数平台上没有“aligned_realloc”?

    MSVC有自己的非标准函数 aligned malloc aligned realloc and aligned free C 17和C11引入了 std aligned alloc 其结果可以是de分配有free or realloc B
  • 将字符串中的“奇怪”字符转换为罗马字符

    我需要能够将用户输入仅转换为 a z 罗马字符 不区分大小写 所以 我感兴趣的角色只有26个 然而 用户可以输入他们想要的任何 形式 的字符 西班牙语 n 法语 e 和德语 u 都可以包含用户输入中的重音符号 这些重音符号会被程序删除 我已
  • 从 C 结构生成 C# 结构

    我有几十个 C 结构 我需要在 C 中使用它们 典型的 C 结构如下所示 typedef struct UM EVENT ULONG32 Id ULONG32 Orgin ULONG32 OperationType ULONG32 Size
  • 如何使用MySqlCommand和prepare语句进行多行插入?(#C)

    Mysql 给出了如何使用准备语句和 NET 插入行的示例 http dev mysql com doc refman 5 5 en connector net programming prepared html http dev mysq
  • 将字符串转换为正确的 URI 格式?

    有没有简单的方法可以将电子邮件地址字符串转换为正确的 URI 格式 Input http mywebsite com validate email 3DE4ED727750215D957F8A1E4B117C38E7250C33 email
  • 带 If 的嵌套 For 循环的时间复杂度

    void f int n for int i 1 i lt n i if i int sqrt n 0 for int k 0 k lt pow i 3 k do something 我的思考过程 执行if语句的次数 sum i 1 to
  • TcpClient 在异步读取期间断开连接

    我有几个关于完成 tcp 连接的问题 客户端使用 Tcp 连接到我的服务器 在接受客户端后listener BeginAcceptTcpClient ConnectionEstabilishedCallback null 我开始阅读netw
  • C# 委托责任链

    为了我的理解目的 我实现了责任链模式 Abstract Base Type public abstract class CustomerServiceDesk protected CustomerServiceDesk nextHandle
  • C# 中的常量和只读? [复制]

    这个问题在这里已经有答案了 可能的重复 const 和 readonly 之间有什么区别 https stackoverflow com questions 55984 what is the difference between cons
  • 为什么要在 C++ 中使用 typedef?

    可以说我有 set
  • 使用 iTextSharp 5.3.3 和 USB 令牌签署 PDF

    我是 iTextSharp 和 StackOverFlow 的新手 我正在尝试使用外部 USB 令牌在 C 中签署 PDF 我尝试使用从互联网上挖掘的以下代码 Org BouncyCastle X509 X509CertificatePar
  • 从 Delphi 调用 C# dll

    我用单一方法编写了 Net 3 5 dll 由Delphi exe调用 不幸的是它不起作用 步骤 1 使用以下代码创建 C 3 5 dll public class MyDllClass public static int MyDllMet
  • Visual Studio 2017 完全支持 C99 吗?

    Visual Studio 的最新版本改进了对 C99 的支持 最新版本VS2017现在支持所有C99吗 如果没有 C99 还缺少哪些功能 No https learn microsoft com en us cpp visual cpp
  • C#中为线程指定特殊的cpu

    我有 2 个线程 我想告诉其中一个在第一个 cpu 上运行 第二个在第二个 cpu 上运行 例如在具有两个 cpu 的机器中 我怎样才能做到这一点 这是我的代码 UCI UCIMain new UCI Thread UCIThread ne
  • 如何使用 C# 以低分辨率形式提供高分辨率图像

    尝试使用 300dpi tif 图像在网络上显示 目前 当用户上传图像时 我正在动态创建缩略图 如果创建的页面引用宽度为 500x500px 的高分辨率图像 我可以使用相同的功能即时转换为 gif jpg 吗 将创建的 jpg 的即将分辨率

随机推荐