⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 win32com.cs

📁 常见的串口通信程序
💻 CS
字号:
namespace SerialPorts
{
    using System;
    using System.Runtime.InteropServices;

    internal class Win32Com
    {
        // Methods
        public Win32Com()
        {
        }

        internal bool Cancel()
        {
            if (!Win32Com.CancelIo(this.handle))
            {
                this.SetFault("CancelIo()");
                return false;
            }
            return true;
        }

        [DllImport("kernel32.dll")]
        private static extern bool CancelIo(IntPtr hFile);

        internal bool Close()//声明函数,用于关闭串行口
        {
            if (!Win32Com.CloseHandle(this.handle))
            {
                this.SetFault("CloseHandle()");
                return false;
            }
            return true;
        }

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);

        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);

        internal bool Flush()
        {
            if (!Win32Com.PurgeComm(this.handle, 15))
            {
                this.SetFault("PurgeComm()");
                return false;
            }
            return true;
        }

        internal bool Open(string portName, bool overlapped)
			//声明一个Open函数,返回bool值,形参为一个字符串(端口名称),一个bool型变量(是否迭交).用于打开端口设备,并返回成功与否。
        {
            if (overlapped)
            {
                this.handle = Win32Com.CreateFile(portName, 0xc0000000, 0, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero);
            }
            else
            {
                this.handle = Win32Com.CreateFile(portName, 0xc0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero);
            }
            if (this.handle == ((IntPtr) (-1)))
            {
                int num1 = Marshal.GetLastWin32Error();
                if (num1 == 5)
                {
                    this.fault = "CreateFile() Failed. Access Denied To " + portName + ".";
                    return false;
                }
                if (num1 == 2)
                {
                    this.fault = "CreateFile() Failed. " + portName + " Is Unavailable Or Invalid.";
                    return false;
                }
                this.SetFault("CreateFile()", num1);
                return false;
            }
            return true;
        }

        [DllImport("kernel32.dll")]
        private static extern bool PurgeComm(IntPtr hFile, uint flags);

        internal bool Read(byte[] buf, uint nToRead, out uint nRead, IntPtr olMem)
        {
            if (!Win32Com.ReadFile(this.handle, buf, nToRead, out nRead, olMem))
            {
                this.SetFault("ReadFile()");
                return false;
            }
            return true;
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint nNumberOfBytesRead, IntPtr lpOverlapped);

        private void SetFault(string who)
        {
            int num1 = Marshal.GetLastWin32Error();
            this.fault = who + " Failed. System Returned Error Code: " + num1.ToString();
        }

        private void SetFault(string who, int err)
        {
            this.fault = who + " Failed. System Returned Error Code: " + err.ToString();
        }

        [DllImport("kernel32.dll")]
        private static extern bool TransmitCommChar(IntPtr hFile, byte cChar);

        internal bool TxChar(byte chr)
        {
            if (!Win32Com.TransmitCommChar(this.handle, chr))
            {
                this.SetFault("TransmitCommChar()");
                return false;
            }
            return true;
        }

        internal bool Write(byte[] buf, uint nToSend, out uint nSent, Win32Ovrlap ovlap)
        {
            bool flag1 = true;
            if (!flag1 && (ovlap.MemPtr != IntPtr.Zero))
            {
                while (this.nUnsent > 0)
                {
                    if (!ovlap.Get(out nSent, true))
                    {
                        continue;
                    }
                    this.nUnsent -= nSent;
                }
            }
            bool flag2 = Win32Com.WriteFile(this.handle, buf, nToSend, out nSent, ovlap.MemPtr);
            this.nUnsent = nToSend - nSent;
            if (!flag2)
            {
                int num1 = Marshal.GetLastWin32Error();
                if (flag1)
                {
                    if (num1 == 0x3e5)
                    {
                        while (this.nUnsent > 0)
                        {
                            if (!ovlap.Get(out nSent, true))
                            {
                                continue;
                            }
                            this.nUnsent -= nSent;
                        }
                        goto Label_00C9;
                    }
                    this.SetFault("WriteFile()", num1);
                    return false;
                }
                if (num1 != 0x3e5)
                {
                    this.SetFault("WriteFile()", num1);
                    return false;
                }
                nSent = nToSend;
            }
        Label_00C9:
            return true;
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern bool WriteFile(IntPtr fFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, IntPtr lpOverlapped);


        // Properties
        internal string Fault
        {
            get
            {
                return this.fault;
            }
        }

        internal IntPtr Handle
        {
            get
            {
                return this.handle;
            }
        }


        // Fields
        internal const uint ERROR_ACCESS_DENIED = 5;
        internal const uint ERROR_FILE_NOT_FOUND = 2;
        internal const uint ERROR_IO_PENDING = 0x3e5;
        private string fault;
        internal const uint FILE_FLAG_OVERLAPPED = 0x40000000;
        internal const uint GENERIC_READ = 0x80000000;
        internal const uint GENERIC_WRITE = 0x40000000;
        private IntPtr handle;
        internal const int INVALID_HANDLE_VALUE = -1;
        private uint nUnsent;
        internal const uint OPEN_EXISTING = 3;
        internal const uint PURGE_RXABORT = 2;
        internal const uint PURGE_RXCLEAR = 8;
        internal const uint PURGE_TXABORT = 1;
        internal const uint PURGE_TXCLEAR = 4;
        internal const uint READ_WRITE = 0xc0000000;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -