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

📄 form1.designer.cs

📁 该程序为PC机与单片机通过RS-232串行口通信的PC端程序
💻 CS
📖 第 1 页 / 共 2 页
字号:
         );

        ///<summary>
        ///读取串口数据
        ///</summary>
        ///<param name="hFile">通信设备句柄</param>
        ///<param name="lpBuffer">数据缓冲区</param>
        ///<param name="nNumberOfBytesToRead">多少字节等待读取</param>
        ///<param name="lpNumberOfBytesRead">读取多少字节</param>
        ///<param name="lpOverlapped">溢出缓冲区</param>
        [DllImport("kernel32.dll")]
        private static extern bool ReadFile(
         int hFile,                // handle to file
         byte[] lpBuffer,             // data buffer
         int nNumberOfBytesToRead,  // number of bytes to read
         ref int lpNumberOfBytesRead, // number of bytes read
         ref OVERLAPPED lpOverlapped    // overlapped buffer
         );

        ///<summary>
        ///写串口数据
        ///</summary>
        ///<param name="hFile">通信设备句柄</param>
        ///<param name="lpBuffer">数据缓冲区</param>
        ///<param name="nNumberOfBytesToWrite">多少字节等待写入</param>
        ///<param name="lpNumberOfBytesWritten">已经写入多少字节</param>
        ///<param name="lpOverlapped">溢出缓冲区</param>
        [DllImport("kernel32.dll")]
        private static extern bool WriteFile(
         int hFile,                    // handle to file
         byte[] lpBuffer,                // data buffer
         int nNumberOfBytesToWrite,     // number of bytes to write
         ref int lpNumberOfBytesWritten,  // number of bytes written
         ref OVERLAPPED lpOverlapped        // overlapped buffer
         );

        ///<summary>
        ///关闭串口
        ///</summary>
        ///<param name="hObject">通信设备句柄</param>
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(
         int hObject   // handle to object
         );

        /*
        ///<summary>
                ///得到串口最后一次返回的错误
                ///</summary>
                [DllImport(DLLPATH)]
                private static extern uint GetLastError();
                #endregion
 
                ///<summary>
                ///设置DCB标志位
                ///</summary>
                ///<param name="whichFlag"></param>
                ///<param name="setting"></param>
                ///<param name="dcb"></param>
                internal void SetDcbFlag(int whichFlag, int setting, DCB dcb)
                {
                    uint num;
                    setting = setting << whichFlag;
                    if ((whichFlag == 4) || (whichFlag == 12))
                    {
                        num = 3;
                    }
                    else if (whichFlag == 15)
                    {
                        num = 0x1ffff;
                    }
                    else
                    {
                        num = 1;
                    }
                    dcb.flags &= ~(num << whichFlag);
                    dcb.flags |= (uint)setting;
                }
        */

        ///<summary>
        ///建立与串口的连接
        ///</summary>
        public void Open()
        {
            DCB dcbCommPort = new DCB();
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();


            // 打开指定串口设备

            //创建端口句柄
            hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

            // IF THE PORT CANNOT BE OPENED, BAIL OUT.
            if (hComm == INVALID_HANDLE_VALUE)
            {
                throw (new ApplicationException("无法打开串口!"));
            }

            // 设置通信超时时间

            GetCommTimeouts(hComm, ref ctoCommPort);
            ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
            ctoCommPort.ReadTotalTimeoutMultiplier = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 0;
            ctoCommPort.WriteTotalTimeoutConstant = 0;
            SetCommTimeouts(hComm, ref ctoCommPort);

            //设置串口参数
            // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
            // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
            // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
            // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
            // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.

            dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
            GetCommState(hComm, ref dcbCommPort);
            dcbCommPort.BaudRate = BaudRate;
            dcbCommPort.Parity = Parity;
            dcbCommPort.ByteSize = ByteSize;
            dcbCommPort.StopBits = StopBits;
            SetCommState(hComm, ref dcbCommPort);

            Opened = true;

        }

        ///<summary>
        ///关闭串口,结束通讯
        ///</summary>
        public void Close()
        {
            if (hComm != INVALID_HANDLE_VALUE)
            {
                CloseHandle(hComm);
                Opened = false;
            }
        }

        ///<summary>
        ///读取串口返回的数据
        ///</summary>
        ///<param name="NumBytes">数据长度</param>
        public byte[] Read(int NumBytes)
        {
            byte[] BufBytes;
            byte[] OutBytes;
            BufBytes = new byte[NumBytes];
            if (hComm != INVALID_HANDLE_VALUE)
            {
                OVERLAPPED ovlCommPort = new OVERLAPPED();
                int BytesRead = 0;
                ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref ovlCommPort);
                OutBytes = new byte[BytesRead];
                Array.Copy(BufBytes, OutBytes, BytesRead);
            }
            else
            {
                throw (new ApplicationException("Comm Port Not Open"));
            }
            return OutBytes;
        }

        ///<summary>
        ///向串口写数据
        ///</summary>
        ///<param name="WriteBytes">数据数组</param
        public int Write(byte[] WriteBytes)
        {
            int BytesWritten = 0;
            if (hComm != INVALID_HANDLE_VALUE)
            {
                OVERLAPPED ovlCommPort = new OVERLAPPED();
                WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);
            }
            else
            {
                throw (new ApplicationException("Comm Port Not Open"));
            }
            return BytesWritten;
        }
    }
   
}

//注意:发送数据包的格式是16进制数据如:02 45 66 FA  中间可以有或者没有空格,但要保证有偶数位

⌨️ 快捷键说明

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