我可以获得我正在使用.net SerialPort类访问的串行端口的设备句柄吗

本文关键字:访问 串行端口 句柄 SerialPort net 我可以 | 更新日期: 2023-09-27 18:00:00

我正在写一个C#。NET应用程序,该应用程序访问公开串行端口接口的USB设备。我在用手电。NET SerialPort类,它工作得很好。

我的问题是,我需要捕获DBT_DEVICEQUERYREMOVE事件,但如果我使用DBT_DEVTYP_DEVICEINTERFACE注册,则无法获得该事件。我确实有DBT_DEVICEARRIVALDBT_DEVICEREMOVECOMPLETE,但没有DBT_DEVICEQUERYREMOVE

从我的网络研究来看,我似乎需要使用DBT_DEVTYP_HANDLE注册,这需要一个句柄,比如CreateFile返回的句柄。由于SerialPort类没有公开这个句柄,我想知道是否有其他方法可以获取句柄(或者其他方法可以获得感兴趣的事件)。

我可以获得我正在使用.net SerialPort类访问的串行端口的设备句柄吗

我认为你可以使用一点反射来获得句柄,我不知道有什么更好的方法可以获得句柄。NET Framework当前正在使用。SerialPort使用一种称为SerialStream的内部类型。此Stream具有您想要的句柄。由于我没有可以测试的串行端口,所以这段代码有点像猜测:

var serialPort = new SerialPort();
object stream = typeof(SerialPort).GetField("internalSerialStream", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(serialPort);
var handle = (SafeFileHandle)stream.GetType().GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(stream);

这将为您提供一个SafeFileHandle,它是句柄的包装器。您可以调用DangerousGetHandle来获得实际的IntPtr

此句柄只有在SerialPort上调用Open之后才具有有效值,并且在释放时变为无效。在使用DangerousGetHandle之前,应该先检查句柄的IsInvalidIsClosed值。

还有一个解决方案是获取的Serialport实现。Net并根据您的喜好进行更改。

这是我为一个需要访问句柄的项目所做的,因为我在SerialPort中遇到了定时/异步问题。所以我把它归结为熊的必需品。

public class SimpleSerialPort : IDisposable
{
    private const uint GenericRead = 0x80000000;
    private const uint GenericWrite = 0x40000000;
    private const int OpenExisting = 3;
    private const uint Setdtr = 5; // Set DTR high
    private FileStream _fileStream;
    public void Close()
    {
        Dispose();
    }
    public int WriteTimeout { get; set; }
    public SafeFileHandle Handle { get; private set; }
    public void Open(string portName, uint baudrate)
    {
        // Check if port can be found
        bool isValid =
            SerialPort.GetPortNames()
                .Any(x => String.Compare(x, portName, StringComparison.OrdinalIgnoreCase) == 0);
        if (!isValid)
        {
            throw new IOException(string.Format("{0} port was not found", portName));
        }
        string port = @"''.'" + portName;
        Handle = CreateFile(port, GenericRead | GenericWrite, 0, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);
        if (Handle.IsInvalid)
        {
            throw new IOException(string.Format("{0} port is already open", portName));
        }
        var dcb = new Dcb();
        // first get the current dcb structure setup
        if (GetCommState(Handle, ref dcb) == false)
        {
            throw new IOException(string.Format("GetCommState error {0}", portName));
        }
        dcb.BaudRate = baudrate;
        dcb.ByteSize = 8;
        dcb.Flags = 129;
        dcb.XoffChar = 0;
        dcb.XonChar = 0;
        /* Apply the settings */
        if (SetCommState(Handle, ref dcb) == false)
        {
            throw new IOException(string.Format("SetCommState error {0}", portName));
        }
        /* Set DTR, some boards needs a DTR = 1 level */
        if (EscapeCommFunction(Handle, Setdtr) == false)
        {
            throw new IOException(string.Format("EscapeCommFunction error {0}", portName));
        }
        // Write default timeouts 
        var cto = new Commtimeouts
        {
            ReadTotalTimeoutConstant = 500,
            ReadTotalTimeoutMultiplier = 0,
            ReadIntervalTimeout = 10,
            WriteTotalTimeoutConstant = WriteTimeout,
            WriteTotalTimeoutMultiplier = 0
        };
        if (SetCommTimeouts(Handle, ref cto) == false)
        {
            throw new IOException(string.Format("SetCommTimeouts error {0}", portName));
        }
        // Create filestream 
        _fileStream = new FileStream(Handle, FileAccess.ReadWrite, 32, false);
    }
    public void Write(byte[] bytes)
    {
        _fileStream.Write(bytes, 0, bytes.Length);
    }
    public void Read(byte[] readArray)
    {
        for (int read = 0; read < readArray.Length;)
        {
            read += _fileStream.Read(readArray, read, readArray.Length - read);
        }
    }
    public byte ReadByte()
    {
        byte[] readsBytes = new byte[1];
        Read(readsBytes);
        return readsBytes[0];
    }
    public void Dispose()
    {
        if (Handle != null)
        {
            Handle.Dispose();
        }
        if (_fileStream != null)
        {
            _fileStream.Dispose();
        }
        _fileStream = null;
        Handle = null;
    }
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode,
        IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool GetCommState(
        SafeFileHandle hFile, // handle to communications device
        ref Dcb lpDcb // device-control block
        );
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetCommState(
        SafeFileHandle hFile, // handle to communications device
        ref Dcb lpDcb // device-control block
        );
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool EscapeCommFunction(
        SafeFileHandle hFile, // handle to communications device
        uint dwFunc
        );
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool SetCommTimeouts(
        SafeFileHandle hFile, // handle to comm device
        ref Commtimeouts lpCommTimeouts // time-out values
        );
    [StructLayout(LayoutKind.Sequential)]
    private struct Commtimeouts
    {
        public int ReadIntervalTimeout;
        public int ReadTotalTimeoutMultiplier;
        public int ReadTotalTimeoutConstant;
        public int WriteTotalTimeoutMultiplier;
        public int WriteTotalTimeoutConstant;
    }
    [StructLayout(LayoutKind.Sequential)]
    private struct Dcb
    {
        private readonly uint DCBlength;
        public uint BaudRate;
        public uint Flags;
        private readonly ushort WReserved;
        private readonly ushort XonLim;
        private readonly ushort XoffLim;
        public byte ByteSize;
        private readonly byte Parity;
        private readonly byte StopBits;
        public byte XonChar;
        public byte XoffChar;
        private readonly byte ErrorChar;
        private readonly byte EofChar;
        private readonly byte EvtChar;
        private readonly ushort WReserved1;
    }
}