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

📄 unsafenativemethods.cs

📁 SerialPort 串口通讯用
💻 CS
字号:
// ==++==
// 
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
/*============================================================
**
** Class:  UnsafeNativeMethods
**
** Purpose: "Container" for all SerialPort/SerialStream-related PInvoke methods
**		  : and hub for all constant definitions considered to be unsafe to the OS.
**		  : Thus here sits the majority of the I/O PInvoke methods as well as 
**		  : those constants typically declared in the unsafe classes.
**		  : Note, that though all relevant methods with the "unsafe" modifier exist here
**		  : but the converse is not true; most methods here are not declared unsafe
**		  : yet manipulate file properites.   
**
** Date:  August 2002
**
===========================================================*/

using System;
using System.Configuration.Assemblies;
using System.Runtime.Remoting;
using System.IO;
using System.Text;
using System.ComponentModel;
using System.Resources;
using System.Runtime;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Threading;

namespace System.IO.Ports
{
	internal sealed class UnsafeNativeMethods
	{
		// All flags for opening a serial communications resource with the Win32 CreateFile()
		internal const int OPEN_EXISTING = 3;
		internal const int OPEN_ALWAYS = 4;
		internal const int FILE_FLAG_NOBUFFERING = 0x500000;
		internal const int FILE_FLAG_OVERLAPPED   = 0x40000000;
		internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
		
		// All file types returned from GetFileType().  We should only be dealing with
		// files of type FILE_TYPE_CHAR.
		internal const int FILE_TYPE_DISK = 1;
		internal const int FILE_TYPE_CHAR = 2;
		internal const int FILE_TYPE_PIPE = 3;

	
		// Declaration for C# representation of Win32 Device Control Block (DCB)
		// structure.  Note that all flag properties are encapsulated in the Flags field here,
		// and accessed/set through SerialStream's GetDcbFlag(...) and SetDcbFlag(...) methods.
		internal struct DCB 
		{
			
			public uint DCBlength; 
			public uint BaudRate; 
			public uint Flags;
			public ushort wReserved; 
			public ushort XonLim; 
			public ushort XoffLim; 
			public byte ByteSize; 
			public byte Parity; 
			public byte StopBits; 
			public byte XonChar; 
			public byte XoffChar; 
			public byte ErrorChar; 
			public byte EofChar; 
			public byte EvtChar; 
			public ushort wReserved1; 
		}

		// Declaration for C# representation of Win32 COMSTAT structure associated with
		// a file handle to a serial communications resource.  SerialStream's 
		// InBufferBytes and OutBufferBytes directly expose cbInQue and cbOutQue to reading, respectively.
		internal struct COMSTAT 
		{
			public uint Flags;
			public uint cbInQue;
			public uint cbOutQue;
		}

		// Declaration for C# representation of Win32 COMMTIMEOUTS
		// structure associated with a file handle to a serial communications resource.
		///Currently the only set fields are ReadTotalTimeoutConstant
		// and WriteTotalTimeoutConstant.		
		internal struct COMMTIMEOUTS 
		{
			public int ReadIntervalTimeout; 
			public int ReadTotalTimeoutMultiplier; 
			public int ReadTotalTimeoutConstant; 
			public int WriteTotalTimeoutMultiplier; 
			public int WriteTotalTimeoutConstant; 
		}

		// Declaration for C# representation of Win32 COMMPROP
		// structure associated with a file handle to a serial communications resource.
		// Currently the only fields used are dwMaxTxQueue, dwMaxRxQueue, and dwMaxBaud
		// to ensure that users provide appropriate settings to the SerialStream constructor.
		internal struct COMMPROP 
		{ 
			public ushort  wPacketLength; 
			public ushort  wPacketVersion; 
			public int dwServiceMask; 
			public int dwReserved1; 
			public int dwMaxTxQueue; 
			public int dwMaxRxQueue; 
			public int dwMaxBaud; 
			public int dwProvSubType; 
			public int dwProvCapabilities; 
			public int dwSettableParams; 
			public int dwSettableBaud; 
			public ushort wSettableData; 
			public ushort  wSettableStopParity; 
			public int dwCurrentTxQueue; 
			public int dwCurrentRxQueue; 
			public int dwProvSpec1; 
			public int dwProvSpec2; 
			public char wcProvChar;
		} 
		

		[StructLayout(LayoutKind.Sequential)]
			internal class SECURITY_ATTRIBUTES 
		{
			internal int nLength = 0;
			internal int lpSecurityDescriptor = 0;
			internal int bInheritHandle = 0;
		}
		

		// Note that each file handle argument is represented as an IntPtr in C#, which is 
		// equivalent to the Win32 HANDLE type.  The NativeMethods class defines INVALID_HANDLE_VALUE
		// as (IntPtr) -1 and NULL as IntPtr.Zero in this regard.
		// All non-unsafe PInvoke methods here require passing structure pointers as passing
		// references in C#, i.e. GetCommState(myFilePointer, ref myDCB).

		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern IntPtr CreateFile(String lpFileName,
			int dwDesiredAccess, int dwShareMode,
			IntPtr securityAttrs, int dwCreationDisposition,
			int dwFlagsAndAttributes, IntPtr hTemplateFile);
    
		[DllImport(NativeMethods.KERNEL32)]
		internal static extern bool CloseHandle(IntPtr handle);

		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool GetCommState(
			IntPtr hFile,  // handle to communications device
			ref DCB lpDCB    // device-control block
			);	
	
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool SetCommState(
			IntPtr hFile,  // handle to communications device
			ref DCB lpDCB    // device-control block
			);		

	
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool GetCommModemStatus(
			IntPtr hFile,        // handle to communications device
			ref int lpModemStat  // control-register values
			);

		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool SetupComm(
			IntPtr hFile,     // handle to communications device
			int dwInQueue,  // size of input buffer
			int dwOutQueue  // size of output buffer
			);
	
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool SetCommTimeouts(
			IntPtr hFile,                  // handle to comm device
			ref COMMTIMEOUTS lpCommTimeouts  // time-out values
			);
		
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool GetCommTimeouts(
			IntPtr hFile,                  // handle to comm device
			ref COMMTIMEOUTS lpCommTimeouts  // time-out values
			);


		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool SetCommBreak(
			IntPtr hFile                 // handle to comm device
			);

		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool ClearCommBreak(
			IntPtr hFile                 // handle to comm device
			);
		
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool ClearCommError(
			IntPtr hFile,                 // handle to comm device
			ref int lpErrors,
			ref COMSTAT lpStat
			);
			
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool PurgeComm(
			IntPtr hFile,  // handle to communications resource
			uint dwFlags  // action to perform
			);

	
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern bool GetCommProperties(
			IntPtr hFile,           // handle to comm device
			ref COMMPROP lpCommProp   // communications properties
			);


		// All actual file Read/Write methods, which are declared to be unsafe.
		[DllImport(NativeMethods.KERNEL32, SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		unsafe internal static extern int ReadFile(IntPtr handle, byte* bytes, int numBytesToRead, out int numBytesRead, NativeOverlapped* overlapped);

		[DllImport(NativeMethods.KERNEL32, SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		unsafe internal static extern int ReadFile(IntPtr handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead, NativeOverlapped* overlapped);
        
		[DllImport(NativeMethods.KERNEL32 , SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		unsafe internal static extern int WriteFile(IntPtr handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, NativeOverlapped* lpOverlapped);

		[DllImport(NativeMethods.KERNEL32 , SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		unsafe internal static extern int WriteFile(IntPtr handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten, NativeOverlapped* lpOverlapped);
		
		[DllImport(NativeMethods.KERNEL32 , SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		internal static extern int GetFileType(
			IntPtr hFile   // handle to file
			);
		[DllImport(NativeMethods.KERNEL32 , SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
		internal static extern bool EscapeCommFunction(
			IntPtr hFile, // handle to communications device
			int dwFunc		// extended function to perform
			);
		
		[DllImport(NativeMethods.KERNEL32 , SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]	
		unsafe internal static extern bool WaitCommEvent(
			IntPtr hFile,                // handle to comm device
			ref int lpEvtMask,           // event type
			NativeOverlapped* lpOverlapped   // overlapped structure 
			);
		
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
		unsafe internal static extern IntPtr CreateEvent(
			IntPtr lpEventAttributes, // SD
			bool bManualReset,                       // reset type
			bool bInitialState,                      // initial state
			String lpName                           // object name
			);
		
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]	
		unsafe internal static extern bool SetCommMask(
			IntPtr hFile,
			int dwEvtMask
		);
		
		
		[DllImport(NativeMethods.KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]	
		internal static extern int WaitForSingleObject(
			IntPtr hHandle,        // handle to object
			int dwMilliseconds   // time-out interval
			);
	}
	
}

⌨️ 快捷键说明

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