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

📄 serialportstream.cs

📁 VC下面的窜口程序
💻 CS
📖 第 1 页 / 共 2 页
字号:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace SerialPortDemo
{
	/// <summary>
	/// Summary description for SerialPortStream.
	/// </summary>
	public class SerialPortStream
	{	
		private const int INVALID_HANDLE_VALUE = -1;
		private const int GENERIC_READ = unchecked((int)0x80000000);
		private const int GENERIC_WRITE = 0x40000000;
		private const int OPEN_EXISTING = 3;

		/// <summary>
		/// What is the size of a byte? 7-bit bytes? 8-bit-bytes? Etc...
		/// </summary>
		public enum DATABITS
		{
			DATABITS_8 = 0x8,
			DATABITS_7 = 0x4,
			DATABITS_6 = 0x2,
			DATABITS_5 = 0x1
		};

		public enum STOPBITS
		{
			/// <summary>
			/// One stop bit.
			/// </summary>
			STOPBITS_1 = 0x1,
			/// <summary>
			/// Setting for 1.5 stop bits.
			/// </summary>
			STOPBITS_15 = 0x2,
			/// <summary>
			/// Two stop bits.
			/// </summary>
			STOPBITS_2 = 0x4
		};

		public enum PARITY
		{
			NONE	= 0,
			ODD		= 1,
			EVEN	= 2,
			MARK	= 3,
			SPACE	= 4
		};
		
		public enum BAUDRATE
		{
			BAUD_110 = 110,
			BAUD_300 = 300,
			BAUD_600 = 600,
			BAUD_1200 = 1200,
			BAUD_2400 = 2400,
			BAUD_4800 = 4800,
			BAUD_9600 = 9600,
			BAUD_14400 = 14400,
			BAUD_19200 = 19200,
			BAUD_38400 = 38400,
			BAUD_56000 = 56000,
			BAUD_57600 = 57600,
			BAUD_115200 = 115200,
			BAUD_128000 = 128000,
			BAUD_256000 = 256000
		};

		[Flags()]
		public enum PURGEFLAGS
		{
			TRANSMIT_CLEAR = 0x4,
			RECIEVE_CLEAR = 0x8
		};

		private int handle = INVALID_HANDLE_VALUE;
		private int port;									// comm port number
		private PARITY parity;								// port parity
		private DATABITS dataBits;							// data bits
		private STOPBITS stopBits;							// stop bits
		private BAUDRATE baudRate;							// port speed
		private int TransmitBufferSize = 512;				// default output buffer size
		private int RecieveBufferSize  = 512;				// default input buffer size
		private int CommunicationTimeout = 100;				// communication timeout (milliseconds)
		
		#region Serial_Port_Specific_Structs
		/// <summary>
		/// This structure defines the control setting for a serial communications device.
		/// </summary>
		private struct DCB
		{
			public int DCBlength;         // Specifies the DCB structure length, in bytes.
			public int BaudRate;          // Specifies the baud rate at which the communication device operates.
			public int Binary;           // Specifies if binary mode is enabled.
			public int ParityEnabled;           // Specifies if parity checking is enabled.
			public int OutxCtsFlow;      // Specifies if the CTS (clear-to-send) signal is monitored for output flow control.
			public int OutxDsrFlow;      // Specifies if the DSR (data-set-ready) signal is monitored for output flow control.
			public int DtrControl;       // Specifies the DTR (data-terminal-ready) flow control.
			public int DsrSensitivity;   // Specifies if the communications driver is sensitive to the state of the DSR signal.
			public int TXContinueOnXoff; // Specifies if transmission stops when the input buffer is full and the driver has transmitted the XoffChar character.
			public int OutX;             // Specifies if XON/XOFF flow control is used during transmission.
			public int InX;              // Specifies if XON/XOFF flow control is used during reception.
			public int ErrorCharEnabled;        // Specifies if bytes received with parity errors are replaced with the character specified by the ErrorChar member.
			public int Null;             // Specifies if null bytes are discarded.
			public int RtsControl;       // Specifies the RTS (request-to-send) flow control.
			public int AbortOnError;     // Specifies if read and write operations are terminated if an error occurs.
			public int Dummy2;           // Reserved; do not use.
			public Int16 Reserved;       // Not used; set to zero.
			public Int16 XonLim;          // Specifies the minimum number of bytes accepted in the input buffer before the XON character is sent.
			public Int16 XoffLim;         // Specifies the maximum number of bytes accepted in the input buffer before the XOFF character is sent.
			public byte ByteSize;         // Specifies the number of bits in the bytes transmitted and received.
			public byte ParityScheme;           // Specifies the parity scheme to be used.
			public byte StopBits;         // Specifies the number of stop bits to be used.
			public char XonChar;          // Specifies the value of the XON character for both transmission and reception.
			public char XoffChar;         // Specifies the value of the XOFF character for both transmission and reception.
			public char ErrorChar;        // Specifies the value of the character used to replace bytes received with a parity error.
			public char EofChar;          // Specifies the value of the character used to signal the end of data.
			public char EvtChar;          // Specifies the value of the character used to signal an event.
			public Int16 Reserved1;      // Reserved; do not use.
		}


		/// <summary>
		/// Structure to set the Serial Port Timeouts.
		/// </summary>
		private struct COMM_TIMEOUTS
		{												  // typedef struct _COMMTIMEOUTS { 
			public int ReadIntervalTimeout;             // Specifies the maximum acceptable time, in milliseconds, to elapse between the arrival of two characters on the communication line.
			public int ReadTotalTimeoutMultiplier;      // Specifies the multiplier, in milliseconds, used to calculate the total time-out period for read operations.
			public int ReadTotalTimeoutconstant;        // Specifies the constant, in milliseconds, used to calculate the total time-out period for read operations.
			public int WriteTotalTimeoutMultiplier;     // Specifies the multiplier, in milliseconds, used to calculate the total time-out period for write operations.
			public int WriteTotalTimeoutconstant;       // Specifies the constant, in milliseconds, used to calculate the total time-out period for write operations.
		}

		private class OVERLAPPED            // typedef struct _OVERLAPPED { 
		{
			public int Internal;			// Reserved for operating system use.
			public int InternalHigh;		// Reserved for operating system use.
			public int Offset;		        // Specifies a file position at which to start the transfer.
			public int OffsetHigh;			// Specifies the high word of the byte offset at which to start the transfer. 
			public int hEvent;		        // Handle to an event set to the signaled state when the operation has been completed.
		}

		#endregion

		
		#region coredll.dll helper functions

		/// <summary>
		/// This function fills in a device-control block (a DCB structure) with
		/// the current control settings for a specified communication device.
		/// </summary>
		/// <param name="handle">File Handle to the serial port device</param>
		/// <param name="deviceControlBlock">A Device Control Block to fill with the current settings.</param>
		/// <returns>Whether the call was successful or not.</returns>
		[DllImport ("coredll.dll")] 
		private static extern int GetCommState(int handle ,out DCB deviceControlBlock);			

		/// <summary>
		/// This function configures a communications device according to the
		/// specifications in a device-control block (a DCB structure). The
		/// function reinitializes all hardware and control settings, but it
		/// does not empty output or input queues
		/// </summary>
		/// <param name="handle">File Handle to the serial port device.</param>
		/// <param name="deviceControlBlock">A Device Control Block to with the new settings.</param>
		/// <returns>Whether the call was successful or not.</returns>
		[DllImport ("coredll.dll")] 
		private static extern int SetCommState(int handle, ref DCB deviceControlBlock);
	
		/// <summary>
		/// /// This function sets the time-out parameters for all read and write
		/// operations on a specified communications device.
		/// </summary>
		/// <param name="handle">File Handle to the serial port device.</param>
		/// <param name="CommTimeouts">COMM_TIMEOUTS structure with the new timeouts for the port.</param>
		/// <returns>Whether the call was successful or not</returns>
		[DllImport ("coredll.dll")] 
		private static extern int SetCommTimeouts(int handle, ref COMM_TIMEOUTS CommTimeouts);

		/// <summary>
		/// This function can discard all characters from the output or input
		/// buffer of a specified communications resource. It can also terminate
		/// pending read or write operations on the resource. 
		/// </summary>
		/// <param name="handle">Handle to the resource to purge.</param>
		/// <param name="purgeFlags">Purge Flags (i.e. Transmit, Recieve, Both)</param>
		/// <returns>Result integer.</returns>
		[DllImport ("coredll.dll")] 
		private static extern int PurgeComm(int handle, PURGEFLAGS purgeFlags);

		/// <summary>
		/// This function initializes the communications parameters for a
		/// specified communications device. 
		/// </summary>
		/// <param name="handle">The handle to the serial port.</param>
		/// <param name="dwInQueue">The Input Queue length</param>
		/// <param name="dwOutQueue">The Output Queue Length</param>
		/// <returns>HRESULT on wether SetupComm failed or succeeded.</returns>
		[DllImport ("coredll.dll")] 
		private static extern int SetupComm(int handle, int dwInQueue, int dwOutQueue);
		
		/// <summary>
		/// This function closes an open object handle
		/// </summary>
		/// <param name="handle">The handle to close</param>
		/// <returns>Whether the call succeeded or not.</returns>
		[DllImport ("coredll.dll")] 
		private static extern int CloseHandle(int handle);

		/// <summary>
		/// Creates a file.

⌨️ 快捷键说明

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