如何在C#中为项目连接串口 [英] How to connect serial port in C# for a project

查看:287
本文介绍了如何在C#中为项目连接串口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



i创建了一个简单的GUI来传递串口,如果项目包含单个Web表单,它会读取文本并给出输出(循环返回)并且执行得很完美,但问题是当我的项目中有多个表单时,我无法连接端口。 (EX:在第一页我有一些按钮,如果我们点击按钮它会转到下一页,在那个页面我想要通信端口)。如何在更多页面中传达serail端口



提前感谢



我有什么尝试过:



i尝试为每个表单添加一个串行连接器,但它没有连接

hello all,

i created a simple GUI which communicate serial port, if the project contains single web form it read the text and gives the output (loop back)and executed perfectly , but the problem is when i have multiple forms in my project i am unable to connect the port. (EX: in the first page i have some buttons if we click on button it goes to next page and in that page i want to communicate the port). how can i communicate serail port in further pages

thanks in advance

What I have tried:

i tried put a serial connector for every form and but it is not connected

推荐答案

一旦打开SerialPort,它就会被锁定,你无法在同一个硬件上打开第二个实例 - 一次只能有一个东西可以控制端口。因此,在表单的最外层创建它,并在创建时将每个表单传递给SerialPort(或其封装类,如果您遵循PIEBALDconsult的指示)的实例 - 最简单的方法是使用接受实例并在创建表单时传递它的构造函数。 (您可以使用 private 构造函数,该构造函数不带参数以保持设计者满意,但确保在不提供实例的情况下无法在应用程序中实例化表单。
Once you open a SerialPort, it is locked and you can't open a second instance on the same hardware - only one "thing" at a time can control the port. So create it in the "outermost" of your forms, and pass the instance of the SerialPort (or its encapsulating class if you follow PIEBALDconsult's directions) to each of the forms as it is created - the simplest way to do that is to use a constructor that accepts an instance and pass it when you create the form. (You can use a private constructor that takes no parameters to keep the designer happy but ensure that the form can't be instantiated in your app without supplying an instance).


问题是您的表单实例正在打开串行端口。只有一个进程和一个SerialPort实例可以在任何时候打开一个端口。因此,Form1的第一个实例获取串行端口。如果它没有关闭端口,则每个新实例都将无法打开端口。它已经在您的表单的第一个实例打开。



在表单代码中使用串口代码是一个非常糟糕的主意。它应该在它自己的类中,管理与串行端口的连接并公开方法,以便任何调用者(您的表单实例)可以告诉它发送数据或从中接收数据的通知。
The problem is that your form instance is holding the serial port open. Only ONE process and ONE SerialPort instance can have a port open at any one time. So, the first instance of your Form1 gets the serial port. If it doesn't close the port, every new instance will not be able to open the port. It's already open by the first instance of your form.

It's a really bad idea to have the serial port code in your form code. It should be in it's own class, managing the connection to the serial port and exposing methods so that any caller (your form instances) can tell it to send data or get notifications from it that data was received.


这篇关于如何在C#中为项目连接串口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆