.net框架的良好串口类?

时间:2009-02-01 04:46:55

标签: .net serial-port

有没有人知道一个好的(希望是免费的)类来替换.net SerialPort类?它引起了我的问题,我需要一个稍微灵活的。

See my other thread about my issues,但实质上我需要在打开端口时禁止发出IOCTL_SERIAL_SET_DTR和IOCTL_SERIAL_CLR_DTR命令,因此我需要比.net框架提供的类更灵活的东西。

3 个答案:

答案 0 :(得分:4)

几年前,在将串行支持添加到.net之前,我使用了OpenNETCF.IO.Serial。它适用于紧凑的框架,但我将它用于紧凑型设备和常规Windows应用程序。你得到了源代码,所以你可以自己修改它,这就是我所做的。

它基本上是在从kernel32.dll导出的串口函数周围创建一个c#包装器。

您可能还想查看How to capture a serial port that disappears because the usb cable gets unplugged

以下是我以前称之为的代码

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

答案 1 :(得分:1)

我没试过试过这个,但也许你可以:

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

答案 2 :(得分:0)

标准.NET SerialPort不是密封类 - 您是否有机会从子类中获得所需的行为?