有谁知道一个好的(希望是免费的)类来替换 .net SerialPort 类?这给我带来了问题,我需要一个稍微灵活一点的。

有关我的问题,请参阅我的其他帖子, ,但本质上我需要在打开端口时抑制发出 IOCTL_SERIAL_SET_DTR 和 IOCTL_SERIAL_CLR_DTR 命令,因此我需要比 .net 框架提供的类更灵活的东西。

有帮助吗?

解决方案

几年前,我用 OpenNETCF.IO.Serial 之前串行支持加入到达网络。这是一个紧凑的框架,但我用了两个紧凑的设备和常规的Windows应用程序。你得到的源代码,这样你可以自己修改,这是我做的。

它基本上围绕创建进口出KERNEL32.DLL的序列功能的C#包装。

您可能也想看看如何捕捉消失,因为USB连接线拔下得到

下面是我用来调用它的代码

     using OpenNETCF.IO.Serial;

     public static Port port;
     private DetailedPortSettings portSettings;
     private Mutex UpdateBusy = new Mutex();

     // create the port
     try
     {
        // create the port settings
        portSettings = new HandshakeNone();
        portSettings.BasicSettings.BaudRate=BaudRates.CBR_9600;

        // create a default port on COM3 with no handshaking
        port = new Port("COM3:", portSettings);

        // define an event handler
        port.DataReceived +=new Port.CommEvent(port_DataReceived);

        port.RThreshold = 1;    
        port.InputLen = 0;      
        port.SThreshold = 1;    
        try
        {
           port.Open();
        }
        catch
        {
           port.Close();
        }
     }
     catch
     {
        port.Close();
     }

     private void port_DataReceived()
     {

        // since RThreshold = 1, we get an event for every character
        byte[] inputData = port.Input;

        // do something with the data
        // note that this is called from a read thread so you should 
        // protect any data pass from here to the main thread using mutex
        // don't forget the use the mutex in the main thread as well
        UpdateBusy.WaitOne();
        // copy data to another data structure
        UpdateBusy.ReleaseMutex();

     }

     private void port_SendBuff()
     {
        byte[] outputData = new byte[esize];
        crc=0xffff;
        j=0;
        outputData[j++]=FS;
        //  .. more code to fill up buff
        outputData[j++]=FS;
        // number of chars sent is determined by size of outputData
        port.Output = outputData;
     }

     // code to close port
     if (port.IsOpen)
     {
        port.Close();
     }
     port.Dispose();

其他提示

我还没有尝试过这个,但是也许你可以:

  • 从获取源代码 System.IO.Ports.SerialPort 通过使用 反射器 或类似的
  • 根据需要更改源代码
  • 在不同的命名空间中重建修改后的副本,并使用它

在标准的.NET的SerialPort不是密封类 - 任何机会,你可以让你从一个子类需要的行为

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top