using System;
using System.Runtime.InteropServices;
using System.Threading;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
/// 110 bps
public const uint BR_110 = 110;
/// 115200 bps
public const uint CBR_115200 = 115200;
/// 1200 bps
public const uint CBR_1200 = 1200;
/// 128000 bps
public const uint CBR_128000 = 128000;
/// 14400 bps
public const uint CBR_14400 = 14400;
/// 19200 bps
public const uint CBR_19200 = 19200;
/// 2400 bps
public const uint CBR_2400 = 2400;
/// 256000 bps
public const uint CBR_256000 = 256000;
/// 300 bps
public const uint CBR_300 = 300;
/// 38400 bps
public const uint CBR_38400 = 38400;
/// 4800 bps
public const uint CBR_4800 = 4800;
/// 57600 bps
public const uint CBR_57600 = 57600;
/// 600 bps
public const uint CBR_600 = 600;
/// 9600 bps
public const uint CBR_9600 = 9600;
/// A mask indicating the type of error.
[Flags]
public enum COMM_ERRS : uint
{
/// The hardware detected a break condition.
CE_BREAK = 0x0010,
/// The hardware detected a framing error.
CE_FRAME = 0x0008,
/// A character-buffer overrun has occurred. The next character is lost.
CE_OVERRUN = 0x0002,
///
/// An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the
/// end-of-file (EOF) character.
///
CE_RXOVER = 0x0001,
/// The hardware detected a parity error.
CE_RXPARITY = 0x0004,
/// Undocumented.
CE_TXFULL = 0x0100,
/// Undocumented.
CE_PTO = 0x0200,
/// Undocumented.
CE_IOE = 0x0400,
/// Undocumented.
CE_DNS = 0x0800,
/// Undocumented.
CE_OOP = 0x1000,
/// Undocumented.
CE_MODE = 0x8000,
}
/// The extended function to be performed.
public enum COMM_ESC_FUNC
{
///
/// Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is
/// identical to the ClearCommBreak function.
///
CLRBREAK = 9,
/// Clears the DTR (data-terminal-ready) signal.
CLRDTR = 6,
/// Clears the RTS (request-to-send) signal.
CLRRTS = 4,
///
/// Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called
/// (or EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical
/// to the SetCommBreak function. Note that this extended function does not flush data that has not been transmitted.
///
SETBREAK = 8,
/// Sends the DTR (data-terminal-ready) signal.
SETDTR = 5,
/// Sends the RTS (request-to-send) signal.
SETRTS = 3,
/// Causes transmission to act as if an XOFF character has been received.
SETXOFF = 1,
/// Causes transmission to act as if an XON character has been received.
SETXON = 2,
}
/// A mask of events that are currently enabled.
[Flags]
public enum COMM_EVT_MASK : uint
{
/// A break was detected on input.
EV_BREAK = 0x0040,
/// The CTS (clear-to-send) signal changed state.
EV_CTS = 0x0008,
/// The DSR (data-set-ready) signal changed state.
EV_DSR = 0x0010,
/// A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_ERR = 0x0080,
/// An event of the first provider-specific type occurred.
EV_EVENT1 = 0x0800,
/// An event of the second provider-specific type occurred.
EV_EVENT2 = 0x1000,
/// A printer error occurred.
EV_PERR = 0x0200,
/// A ring indicator was detected.
EV_RING = 0x0100,
/// The RLSD (receive-line-signal-detect) signal changed state.
EV_RLSD = 0x0020,
/// The receive buffer is 80 percent full.
EV_RX80FULL = 0x0400,
/// A character was received and placed in the input buffer.
EV_RXCHAR = 0x0001,
///
/// The event character was received and placed in the input buffer. The event character is specified in the device's DCB
/// structure, which is applied to a serial port by using the SetCommState function.
///
EV_RXFLAG = 0x0002,
/// The last character in the output buffer was sent.
EV_TXEMPTY = 0x0004,
}
/// The current state of the modem control-register values.
[Flags]
public enum COMM_MODEM_STATUS : uint
{
/// The CTS (clear-to-send) signal is on.
MS_CTS_ON = 0x0010,
/// The DSR (data-set-ready) signal is on.
MS_DSR_ON = 0x0020,
/// The ring indicator signal is on.
MS_RING_ON = 0x0040,
/// The RLSD (receive-line-signal-detect) signal is on.
MS_RLSD_ON = 0x0080,
}
/// PurgeComm flags
[Flags]
public enum COMM_PURGE
{
///
/// Terminates all outstanding overlapped read operations and returns immediately, even if the read operations have not been completed.
///
PURGE_RXABORT = 0x0002,
/// Clears the input buffer (if the device driver has one).
PURGE_RXCLEAR = 0x0008,
///
/// Terminates all outstanding overlapped write operations and returns immediately, even if the write operations have not been completed.
///
PURGE_TXABORT = 0x0001,
/// Clears the output buffer (if the device driver has one).
PURGE_TXCLEAR = 0x0004,
}
///
[Flags]
public enum COMM_SET_DATA : ushort
{
/// 5 data bits
DATABITS_5 = 0x0001,
/// 6 data bits
DATABITS_6 = 0x0002,
/// 7 data bits
DATABITS_7 = 0x0004,
/// 8 data bits
DATABITS_8 = 0x0008,
/// 16 data bits
DATABITS_16 = 0x0010,
/// Special wide path through serial hardware lines
DATABITS_16X = 0x0020,
}
///
[Flags]
public enum COMM_SET_PARAMS : uint
{
/// Baud rate
SP_BAUD = 0x0002,
/// Data bits
SP_DATABITS = 0x0004,
/// Handshaking (flow control)
SP_HANDSHAKING = 0x0010,
/// Parity
SP_PARITY = 0x0001,
/// Parity checking
SP_PARITY_CHECK = 0x0020,
/// RLSD (receive-line-signal-detect)
SP_RLSD = 0x0040,
/// Stop bits
SP_STOPBITS = 0x0008,
}
///
[Flags]
public enum COMM_STOP_PARITY : ushort
{
/// 1 stop bit
STOPBITS_10 = 0x0001,
/// 1.5 stop bits
STOPBITS_15 = 0x0002,
/// 2 stop bits
STOPBITS_20 = 0x0004,
/// No parity
PARITY_NONE = 0x0100,
/// Odd parity
PARITY_ODD = 0x0200,
/// Even parity
PARITY_EVEN = 0x0400,
/// Mark parity
PARITY_MARK = 0x0800,
/// Space parity
PARITY_SPACE = 0x1000,
}
/// The DTR (data-terminal-ready) flow control.
public enum DTR_CONTROL
{
/// Disables the DTR line when the device is opened and leaves it disabled.
DTR_CONTROL_DISABLE = 0x00,
/// Enables the DTR line when the device is opened and leaves it on.
DTR_CONTROL_ENABLE = 0x01,
///
/// Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the
/// EscapeCommFunction function.
///
DTR_CONTROL_HANDSHAKE = 0x02,
}
/// Parity scheme for comm settings.
public enum Parity : byte
{
/// Even parity.
EVENPARITY = 2,
/// Mark parity.
MARKPARITY = 3,
/// No parity.
NOPARITY = 0,
/// Odd parity.
ODDPARITY = 1,
/// Space parity.
SPACEPARITY = 4,
}
/// A bitmask indicating the capabilities offered by the provider.
[Flags]
public enum PROV_CAPABILITIES : uint
{
/// Special 16-bit mode supported
PCF_16BITMODE = 0x0200,
/// DTR (data-terminal-ready)/DSR (data-set-ready) supported
PCF_DTRDSR = 0x0001,
/// Interval time-outs supported
PCF_INTTIMEOUTS = 0x0080,
/// Parity checking supported
PCF_PARITY_CHECK = 0x0008,
/// RLSD (receive-line-signal-detect) supported
PCF_RLSD = 0x0004,
/// RTS (request-to-send)/CTS (clear-to-send) supported
PCF_RTSCTS = 0x0002,
/// Settable XON/XOFF supported
PCF_SETXCHAR = 0x0020,
/// Special character support provided
PCF_SPECIALCHARS = 0x0100,
/// The total (elapsed) time-outs supported
PCF_TOTALTIMEOUTS = 0x0040,
/// XON/XOFF flow control supported
PCF_XONXOFF = 0x0010,
}
/// The type of communications provider
public enum PROV_SUB_TYPE : uint
{
/// FAX device
PST_FAX = 0x00000021,
/// LAT protocol
PST_LAT = 0x00000101,
/// Modem device
PST_MODEM = 0x00000006,
/// Unspecified network bridge
PST_NETWORK_BRIDGE = 0x00000100,
/// Parallel port
PST_PARALLELPORT = 0x00000002,
/// RS-232 serial port
PST_RS232 = 0x00000001,
/// RS-422 port
PST_RS422 = 0x00000003,
/// RS-423 port
PST_RS423 = 0x00000004,
/// RS-449 port
PST_RS449 = 0x00000005,
/// Scanner device
PST_SCANNER = 0x00000022,
/// TCP/IP Telnet protocol
PST_TCPIP_TELNET = 0x00000102,
/// Unspecified
PST_UNSPECIFIED = 0x00000000,
/// X.25 standards
PST_X25 = 0x00000103,
}
/// The DTR (data-terminal-ready) flow control.
public enum RTS_CONTROL
{
/// Disables the RTS line when the device is opened and leaves it disabled.
RTS_CONTROL_DISABLE = 0x00,
/// Enables the RTS line when the device is opened and leaves it on.
RTS_CONTROL_ENABLE = 0x01,
///
/// Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than one-half full and
/// lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an error for the
/// application to adjust the line by using the EscapeCommFunction function.
///
RTS_CONTROL_HANDSHAKE = 0x02,
///
/// Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent,
/// the RTS line will be low.
///
RTS_CONTROL_TOGGLE = 0x03,
}
/// Stop bits for comm settings.
public enum StopBits : byte
{
/// 1 stop bit.
ONESTOPBIT = 0,
/// 1.5 stop bits.
ONE5STOPBITS = 1,
/// 2 stop bits.
TWOSTOPBITS = 2,
}
///
/// Fills a specified DCB structure with values specified in a device-control string. The device-control string uses the
/// syntax of the mode command.
///
///
///
/// The device-control information. The function takes this string, parses it, and then sets appropriate values in the DCB
/// structure pointed to by lpDCB.
///
/// The string must have the same form as the mode command's command-line arguments:
/// COMx[:][baud=b][parity=p][data=d][stop=s][to={on|off}][xon={on|off}][odsr={on|off}][octs={on|off}][dtr={on|off|hs}][rts={on|off|hs|tg}][idsr={on|off}]
/// The device name is optional, but it must specify a valid device if used.
/// For example, the following string specifies a baud rate of 1200, no parity, 8 data bits, and 1 stop bit:
///
/// A pointer to a DCB structure that receives the information.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI BuildCommDCB( _In_ LPCTSTR lpDef, _Out_ LPDCB lpDCB); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363143(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363143")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BuildCommDCB(string lpDef, out DCB lpDCB);
///
/// Translates a device-definition string into appropriate device-control block codes and places them into a device control block.
/// The function can also set up time-out values, including the possibility of no time-outs, for a device; the function's behavior in
/// this regard depends on the contents of the device-definition string.
///
///
///
/// The device-control information. The function takes this string, parses it, and then sets appropriate values in the DCB
/// structure pointed to by lpDCB.
///
/// The string must have the same form as the mode command's command-line arguments:
///
/// COM x[ :][ baud={ 11| 110| 15| 150| 30| 300| 60|
/// 600| 12| 1200| 24| 2400| 48| 4800| 96| 9600| 19|
/// 19200}][ parity={ n| e| o| m| s}][ data={ 5| 6| 7|
/// 8}][ stop={ 1| 1.5| 2}][ to={ on| off}][ xon={ on|
/// off}][ odsr={ on| off}][ octs={ on| off}][ dtr={ on| off|
/// hs}][ rts={ on| off| hs| tg}][ idsr={ on| off}]
///
///
/// The "baud" substring can be any of the values listed, which are in pairs. The two-digit values are the first two digits of the
/// associated values that they represent. For example, 11 represents 110 baud, 19 represents 19,200 baud.
///
///
/// The "parity" substring indicates how the parity bit is used to detect transmission errors. The values represent "none", "even",
/// "odd", "mark", and "space".
///
/// For more information, see the Mode command reference in TechNet.
/// For example, the following string specifies a baud rate of 1200, no parity, 8 data bits, and 1 stop bit:
///
///
/// A pointer to a DCB structure that receives information from the device-control information string pointed to by lpDef.
/// This DCB structure defines the control settings for a communications device.
///
/// A pointer to a COMMTIMEOUTS structure that receives time-out information.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI BuildCommDCBAndTimeouts( _In_ LPCTSTR lpDef, _Out_ LPDCB lpDCB, _Out_ LPCOMMTIMEOUTS lpCommTimeouts); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363145(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363145")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BuildCommDCBAndTimeouts(string lpDef, out DCB lpDCB, out COMMTIMEOUTS lpCommTimeouts);
///
/// Restores character transmission for a specified communications device and places the transmission line in a nonbreak state.
///
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI ClearCommBreak( _In_ HANDLE hFile); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363179(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363179")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ClearCommBreak([In] HFILE hFile);
///
/// Retrieves information about a communications error and reports the current status of a communications device. The function is
/// called when a communications error occurs, and it clears the device's error flag to enable additional input and output (I/O) operations.
///
/// A handle to the communications device. The CreateFile function returns this handle.
///
///
/// A pointer to a variable that receives a mask indicating the type of error. This parameter can be one or more of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// CE_BREAK0x0010
/// The hardware detected a break condition.
///
/// -
/// CE_FRAME0x0008
/// The hardware detected a framing error.
///
/// -
/// CE_OVERRUN0x0002
/// A character-buffer overrun has occurred. The next character is lost.
///
/// -
/// CE_RXOVER0x0001
///
/// An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the
/// end-of-file (EOF) character.
///
///
/// -
/// CE_RXPARITY0x0004
/// The hardware detected a parity error.
///
///
///
/// The following values are not supported:
///
///
/// A pointer to a COMSTAT structure in which the device's status information is returned. If this parameter is NULL,
/// no status information is returned.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI ClearCommError( _In_ HANDLE hFile, _Out_opt_ LPDWORD lpErrors, _Out_opt_ LPCOMSTAT lpStat); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363180(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363180")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ClearCommError([In] HFILE hFile, out COMM_ERRS lpErrors, out COMSTAT lpStat);
/// Displays a driver-supplied configuration dialog box.
///
/// The name of the device for which a dialog box should be displayed. For example, COM1 through COM9 are serial ports and LPT1
/// through LPT9 are parallel ports.
///
///
/// A handle to the window that owns the dialog box. This parameter can be any valid window handle, or it should be NULL if
/// the dialog box is to have no owner.
///
///
/// A pointer to a COMMCONFIG structure. This structure contains initial settings for the dialog box before the call, and
/// changed values after the call.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI CommConfigDialog( _In_ LPCTSTR lpszName, _In_ HWND hWnd, _Inout_ LPCOMMCONFIG lpCC); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363187(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363187")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CommConfigDialog(string lpszName, [In] HWND hWnd, ref COMMCONFIG lpCC);
/// Directs the specified communications device to perform an extended function.
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// The extended function to be performed. This parameter can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// CLRBREAK9
///
/// Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is
/// identical to the ClearCommBreak function.
///
///
/// -
/// CLRDTR6
/// Clears the DTR (data-terminal-ready) signal.
///
/// -
/// CLRRTS4
/// Clears the RTS (request-to-send) signal.
///
/// -
/// SETBREAK8
///
/// Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called (or
/// EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical to the
/// SetCommBreak function. Note that this extended function does not flush data that has not been transmitted.
///
///
/// -
/// SETDTR5
/// Sends the DTR (data-terminal-ready) signal.
///
/// -
/// SETRTS3
/// Sends the RTS (request-to-send) signal.
///
/// -
/// SETXOFF1
/// Causes transmission to act as if an XOFF character has been received.
///
/// -
/// SETXON2
/// Causes transmission to act as if an XON character has been received.
///
///
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI EscapeCommFunction( _In_ HANDLE hFile, _In_ DWORD dwFunc); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363254(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363254")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EscapeCommFunction([In] HFILE hFile, COMM_ESC_FUNC dwFunc);
///
/// Retrieves the current configuration of a communications device.
/// To retrieve the default configuration settings from the device manager, use the GetDefaultCommConfig function.
///
/// A handle to the open communications device. The CreateFile function returns this handle.
/// A pointer to a buffer that receives a COMMCONFIG structure.
///
/// The size, in bytes, of the buffer pointed to by lpCC. When the function returns, the variable contains the number of bytes copied
/// if the function succeeds, or the number of bytes required if the buffer was too small.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, use the GetLastError function.
///
// BOOL WINAPI GetCommConfig( _In_ HANDLE hCommDev, _Out_ LPCOMMCONFIG lpCC, _Inout_ LPDWORD lpdwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363256(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363256")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommConfig([In] HFILE hCommDev, SafeAllocatedMemoryHandle lpCC, ref uint lpdwSize);
/// Retrieves the value of the event mask for a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
///
///
/// A pointer to the variable that receives a mask of events that are currently enabled. This parameter can be one or more of the
/// following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// EV_BREAK0x0040
/// A break was detected on input.
///
/// -
/// EV_CTS0x0008
/// The CTS (clear-to-send) signal changed state.
///
/// -
/// EV_DSR0x0010
/// The DSR (data-set-ready) signal changed state.
///
/// -
/// EV_ERR0x0080
/// A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
///
/// -
/// EV_EVENT10x0800
/// An event of the first provider-specific type occurred.
///
/// -
/// EV_EVENT20x1000
/// An event of the second provider-specific type occurred.
///
/// -
/// EV_PERR0x0200
/// A printer error occurred.
///
/// -
/// EV_RING0x0100
/// A ring indicator was detected.
///
/// -
/// EV_RLSD0x0020
/// The RLSD (receive-line-signal-detect) signal changed state.
///
/// -
/// EV_RX80FULL0x0400
/// The receive buffer is 80 percent full.
///
/// -
/// EV_RXCHAR0x0001
/// A character was received and placed in the input buffer.
///
/// -
/// EV_RXFLAG0x0002
///
/// The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure,
/// which is applied to a serial port by using the SetCommState function.
///
///
/// -
/// EV_TXEMPTY0x0004
/// The last character in the output buffer was sent.
///
///
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI GetCommMask( _In_ HANDLE hFile, _Out_ LPDWORD lpEvtMask); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363257(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363257")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommMask([In] HFILE hFile, out COMM_EVT_MASK lpEvtMask);
/// Retrieves the modem control-register values.
/// A handle to the communications device. The CreateFile function returns this handle.
///
///
/// A pointer to a variable that receives the current state of the modem control-register values. This parameter can be one or more
/// of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// MS_CTS_ON0x0010
/// The CTS (clear-to-send) signal is on.
///
/// -
/// MS_DSR_ON0x0020
/// The DSR (data-set-ready) signal is on.
///
/// -
/// MS_RING_ON0x0040
/// The ring indicator signal is on.
///
/// -
/// MS_RLSD_ON0x0080
/// The RLSD (receive-line-signal-detect) signal is on.
///
///
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI GetCommModemStatus( _In_ HANDLE hFile, _Out_ LPDWORD lpModemStat); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363258(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363258")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommModemStatus([In] HFILE hFile, out COMM_MODEM_STATUS lpModemStat);
///
/// Gets an array that contains the well-formed COM ports.
///
/// This function obtains the COM port numbers from the HKLM\Hardware\DeviceMap\SERIALCOMM registry key and then writes them
/// to a caller-supplied array. If the array is too small, the function gets the necessary size.
///
/// Note If new entries are added to the registry key, the necessary size can change between API calls.
///
///
/// An array for the port numbers.
///
///
/// The length of the array in the lpPortNumbers parameter.
///
///
/// The number of port numbers written to the lpPortNumbers or the length of the array required for the port numbers.
///
///
///
///
/// Return code
/// Description
///
/// -
/// ERROR_SUCCESS
/// The call succeeded. The lpPortNumbers array was large enough for the result.
///
/// -
/// ERROR_MORE_DATA
/// The lpPortNumbers array was too small to contain all available port numbers.
///
/// -
/// ERROR_FILE_NOT_FOUND
/// There are no comm ports available.
///
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-getcommports ULONG GetCommPorts( PULONG lpPortNumbers,
// ULONG uPortNumbersCount, PULONG puPortNumbersFound );
[DllImport(Lib.KernelBase, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winbase.h", MSDNShortId = "8E57FB62-D7A0-4B47-942B-E33E0B7A37B1", MinClient = PInvokeClient.Windows10)]
public static extern Win32Error GetCommPorts([In, Out] uint[] lpPortNumbers, uint uPortNumbersCount, out uint puPortNumbersFound);
///
/// Gets an array that contains the well-formed COM ports.
///
/// This function obtains the COM port numbers from the HKLM\Hardware\DeviceMap\SERIALCOMM registry key and then writes them
/// to a caller-supplied array.
///
/// Note If new entries are added to the registry key, the necessary size can change between API calls.
///
/// An array of port numbers.
[PInvokeData("winbase.h", MSDNShortId = "8E57FB62-D7A0-4B47-942B-E33E0B7A37B1", MinClient = PInvokeClient.Windows10)]
public static uint[] GetCommPorts()
{
Win32Error err;
if ((err = GetCommPorts(null, 0, out var c)).Failed && err != Win32Error.ERROR_MORE_DATA)
throw err.GetException();
var ports = new uint[c];
GetCommPorts(ports, c, out _).ThrowIfFailed();
return ports;
}
/// Retrieves information about the communications properties for a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// A pointer to a COMMPROP structure in which the communications properties information is returned. This information can be
/// used in subsequent calls to the SetCommState, SetCommTimeouts, or SetupComm function to configure the
/// communications device.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI GetCommProperties( _In_ HANDLE hFile, _Out_ LPCOMMPROP lpCommProp); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363259(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363259")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommProperties([In] HFILE hFile, out COMMPROP lpCommProp);
/// Retrieves the current control settings for a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
/// A pointer to a DCB structure that receives the control settings information.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI GetCommState( _In_ HANDLE hFile, _Inout_ LPDCB lpDCB); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363260(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363260")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommState([In] HFILE hFile, out DCB lpDCB);
/// Retrieves the time-out parameters for all read and write operations on a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
/// A pointer to a COMMTIMEOUTS structure in which the time-out information is returned.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI GetCommTimeouts( _In_ HANDLE hFile, _Out_ LPCOMMTIMEOUTS lpCommTimeouts); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363261(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363261")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCommTimeouts([In] HFILE hFile, out COMMTIMEOUTS lpCommTimeouts);
/// Retrieves the default configuration for the specified communications device.
///
/// The name of the device. For example, COM1 through COM9 are serial ports and LPT1 through LPT9 are parallel ports.
///
/// A pointer to a buffer that receives a COMMCONFIG structure.
///
/// A pointer to a variable that specifies the size of the buffer pointed to by lpCC, in bytes. Upon return, the variable contains
/// the number of bytes copied if the function succeeds, or the number of bytes required if the buffer was too small.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, use the GetLastError function.
///
// BOOL WINAPI GetDefaultCommConfig( _In_ LPCTSTR lpszName, _Out_ LPCOMMCONFIG lpCC, _Inout_ LPDWORD lpdwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363262(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363262")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDefaultCommConfig(string lpszName, SafeAllocatedMemoryHandle lpCC, ref uint lpdwSize);
///
/// Attempts to open a communication device.
///
///
/// A one-based port number for the communication device to open.
///
///
/// The requested access to the device.
/// For more information about requested access, see CreateFile and Creating and Opening Files.
///
///
/// The requested flags and attributes to the device.
/// Note For this function, only values of FILE_FLAG_OVERLAPPED or 0x0 are expected for this parameter.
///
///
/// Value
/// Meaning
///
/// -
/// FILE_FLAG_OVERLAPPED 0x40000000
/// The file or device is being opened or created for asynchronous I/O.
///
///
///
///
/// If the function succeeds, the function returns a valid HANDLE. Use CloseHandle to close that handle.
/// If an error occurs, the function returns INVALID_HANDLE_VALUE.
///
///
///
/// The uPortNumber parameter accepts one-based values. A value of 1 for uPortNumber causes this function to attempt to open COM1.
///
/// To support UWP, link against WindowsApp.lib.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-opencommport HANDLE OpenCommPort( ULONG uPortNumber, DWORD
// dwDesiredAccess, DWORD dwFlagsAndAttributes );
[DllImport(Lib.KernelBase, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winbase.h", MSDNShortId = "D96D3F6D-2158-4E6A-84A8-DC3BAE9624FA")]
public static extern SafeHFILE OpenCommPort(uint uPortNumber, FileAccess dwDesiredAccess, uint dwFlagsAndAttributes);
///
/// Discards 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.
///
/// A handle to the communications resource. The CreateFile function returns this handle.
///
/// This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// PURGE_RXABORT0x0002
///
/// Terminates all outstanding overlapped read operations and returns immediately, even if the read operations have not been completed.
///
///
/// -
/// PURGE_RXCLEAR0x0008
/// Clears the input buffer (if the device driver has one).
///
/// -
/// PURGE_TXABORT0x0001
///
/// Terminates all outstanding overlapped write operations and returns immediately, even if the write operations have not been completed.
///
///
/// -
/// PURGE_TXCLEAR0x0004
/// Clears the output buffer (if the device driver has one).
///
///
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI PurgeComm( _In_ HANDLE hFile, _In_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363428(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363428")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PurgeComm([In] HFILE hFile, COMM_PURGE dwFlags);
///
/// Suspends character transmission for a specified communications device and places the transmission line in a break state until the
/// ClearCommBreak function is called.
///
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetCommBreak( _In_ HANDLE hFile); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363433(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363433")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCommBreak([In] HFILE hFile);
/// Sets the current configuration of a communications device.
/// A handle to the open communications device. The CreateFile function returns this handle.
/// A pointer to a COMMCONFIG structure.
/// The size of the structure pointed to by lpCC, in bytes.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetCommConfig( _In_ HANDLE hCommDev, _In_ LPCOMMCONFIG lpCC, _In_ DWORD dwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363434(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363434")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCommConfig([In] HFILE hCommDev, [In] SafeAllocatedMemoryHandle lpCC, uint dwSize);
/// Specifies a set of events to be monitored for a communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// The events to be enabled. A value of zero disables all events. This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// EV_BREAK0x0040
/// A break was detected on input.
///
/// -
/// EV_CTS0x0008
/// The CTS (clear-to-send) signal changed state.
///
/// -
/// EV_DSR0x0010
/// The DSR (data-set-ready) signal changed state.
///
/// -
/// EV_ERR0x0080
/// A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
///
/// -
/// EV_RING0x0100
/// A ring indicator was detected.
///
/// -
/// EV_RLSD0x0020
/// The RLSD (receive-line-signal-detect) signal changed state.
///
/// -
/// EV_RXCHAR0x0001
/// A character was received and placed in the input buffer.
///
/// -
/// EV_RXFLAG0x0002
///
/// The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure,
/// which is applied to a serial port by using the SetCommState function.
///
///
/// -
/// EV_TXEMPTY0x0004
/// The last character in the output buffer was sent.
///
///
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetCommMask( _In_ HANDLE hFile, _In_ DWORD dwEvtMask); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363435(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363435")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCommMask([In] HFILE hFile, COMM_EVT_MASK dwEvtMask);
///
/// 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.
///
/// A handle to the communications device. The CreateFile function returns this handle.
///
/// A pointer to a DCB structure that contains the configuration information for the specified communications device.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetCommState( _In_ HANDLE hFile, _In_ LPDCB lpDCB); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363436(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363436")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCommState([In] HFILE hFile, in DCB lpDCB);
/// Sets the time-out parameters for all read and write operations on a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
/// A pointer to a COMMTIMEOUTS structure that contains the new time-out values.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetCommTimeouts( _In_ HANDLE hFile, _In_ LPCOMMTIMEOUTS lpCommTimeouts); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363437(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363437")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCommTimeouts([In] HFILE hFile, in COMMTIMEOUTS lpCommTimeouts);
/// Sets the default configuration for a communications device.
///
/// The name of the device. For example, COM1 through COM9 are serial ports and LPT1 through LPT9 are parallel ports.
///
/// A pointer to a COMMCONFIG structure.
/// The size of the structure pointed to by lpCC, in bytes.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetDefaultCommConfig( _In_ LPCTSTR lpszName, _In_ LPCOMMCONFIG lpCC, _In_ DWORD dwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363438(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363438")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDefaultCommConfig(string lpszName, [In] SafeAllocatedMemoryHandle lpCC, uint dwSize);
/// Initializes the communications parameters for a specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
/// The recommended size of the device's internal input buffer, in bytes.
/// The recommended size of the device's internal output buffer, in bytes.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI SetupComm( _In_ HANDLE hFile, _In_ DWORD dwInQueue, _In_ DWORD dwOutQueue); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363439(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363439")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetupComm([In] HFILE hFile, uint dwInQueue, uint dwOutQueue);
/// Transmits a specified character ahead of any pending data in the output buffer of the specified communications device.
/// A handle to the communications device. The CreateFile function returns this handle.
/// The character to be transmitted.
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI TransmitCommChar( _In_ HANDLE hFile, _In_ char cChar); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363473(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363473")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool TransmitCommChar([In] HFILE hFile, byte cChar);
///
/// Waits for an event to occur for a specified communications device. The set of events that are monitored by this function is
/// contained in the event mask associated with the device handle.
///
/// A handle to the communications device. The CreateFile function returns this handle.
///
///
/// A pointer to a variable that receives a mask indicating the type of event that occurred. If an error occurs, the value is zero;
/// otherwise, it is one of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// EV_BREAK0x0040
/// A break was detected on input.
///
/// -
/// EV_CTS0x0008
/// The CTS (clear-to-send) signal changed state.
///
/// -
/// EV_DSR0x0010
/// The DSR (data-set-ready) signal changed state.
///
/// -
/// EV_ERR0x0080
/// A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
///
/// -
/// EV_RING0x0100
/// A ring indicator was detected.
///
/// -
/// EV_RLSD0x0020
/// The RLSD (receive-line-signal-detect) signal changed state.
///
/// -
/// EV_RXCHAR0x0001
/// A character was received and placed in the input buffer.
///
/// -
/// EV_RXFLAG0x0002
///
/// The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure,
/// which is applied to a serial port by using the SetCommState function.
///
///
/// -
/// EV_TXEMPTY0x0004
/// The last character in the output buffer was sent.
///
///
///
///
///
/// A pointer to an OVERLAPPED structure. This structure is required if hFile was opened with FILE_FLAG_OVERLAPPED.
///
/// If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a
/// valid OVERLAPPED structure. If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the
/// function can incorrectly report that the operation is complete.
///
///
/// If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, WaitCommEvent is performed as an
/// overlapped operation. In this case, the OVERLAPPED structure must contain a handle to a manual-reset event object (created
/// by using the CreateEvent function).
///
///
/// If hFile was not opened with FILE_FLAG_OVERLAPPED, WaitCommEvent does not return until one of the specified events
/// or an error occurs.
///
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
///
// BOOL WINAPI WaitCommEvent( _In_ HANDLE hFile, _Out_ LPDWORD lpEvtMask, _In_ LPOVERLAPPED lpOverlapped); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363479(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363479")]
[return: MarshalAs(UnmanagedType.Bool)]
public static unsafe extern bool WaitCommEvent([In] HFILE hFile, out COMM_EVT_MASK lpEvtMask, NativeOverlapped* lpOverlapped);
///
/// Contains information about the configuration state of a communications device.
///
// typedef struct _COMM_CONFIG { DWORD dwSize; WORD wVersion; WORD wReserved; DCB dcb; DWORD dwProviderSubType; DWORD
// dwProviderOffset; DWORD dwProviderSize; WCHAR wcProviderData[1];} COMMCONFIG, *LPCOMMCONFIG;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 2)]
[PInvokeData("Winbase.h", MSDNShortId = "aa363188")]
public struct COMMCONFIG
{
///
/// The size of the structure, in bytes. The caller must set this member to .
///
public uint dwSize;
///
///
/// The version number of the structure. This parameter can be 1. The version of the provider-specific structure should be
/// included in the wcProviderData member.
///
///
public ushort wVersion;
///
/// Reserved; do not use.
///
public ushort wReserved;
///
///
/// The device-control block ( DCB) structure for RS-232 serial devices. A DCB structure is always present
/// regardless of the port driver subtype specified in the device's COMMPROP structure.
///
///
public DCB dcb;
///
///
/// The type of communications provider, and thus the format of the provider-specific data. For a list of communications provider
/// types, see the description of the COMMPROP structure.
///
///
public PROV_SUB_TYPE dwProviderSubType;
///
///
/// The offset of the provider-specific data relative to the beginning of the structure, in bytes. This member is zero if there
/// is no provider-specific data.
///
///
public uint dwProviderOffset;
///
/// The size of the provider-specific data, in bytes.
///
public uint dwProviderSize;
///
///
/// Optional provider-specific data. This member can be of any size or can be omitted. Because the COMMCONFIG structure
/// may be expanded in the future, applications should use the dwProviderOffset member to determine the location of this member.
///
///
public IntPtr wcProviderData;
/// Gets a default instance with the size field set.
public static readonly COMMCONFIG Default = new COMMCONFIG { dwSize = (uint)Marshal.SizeOf(typeof(COMMCONFIG)), wVersion = 1, dcb = DCB.Default };
}
/// Contains information about a communications driver.
// typedef struct _COMMPROP { WORD wPacketLength; WORD wPacketVersion; DWORD dwServiceMask; DWORD dwReserved1; DWORD dwMaxTxQueue;
// DWORD dwMaxRxQueue; DWORD dwMaxBaud; DWORD dwProvSubType; DWORD dwProvCapabilities; DWORD dwSettableParams; DWORD dwSettableBaud;
// WORD wSettableData; WORD wSettableStopParity; DWORD dwCurrentTxQueue; DWORD dwCurrentRxQueue; DWORD dwProvSpec1; DWORD
// dwProvSpec2; WCHAR wcProvChar[1];} COMMPROP,
// *LPCOMMPROP; https://msdn.microsoft.com/en-us/library/windows/desktop/aa363189(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "aa363189")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 2)]
public struct COMMPROP
{
/// The size of the entire data packet, regardless of the amount of data requested, in bytes.
public ushort wPacketLength;
/// The version of the structure.
public ushort wPacketVersion;
///
/// A bitmask indicating which services are implemented by this provider. The SP_SERIALCOMM value is always specified for
/// communications providers, including modem providers.
///
public uint dwServiceMask;
/// Reserved; do not use.
public uint dwReserved1;
///
/// The maximum size of the driver's internal output buffer, in bytes. A value of zero indicates that no maximum value is imposed
/// by the serial provider.
///
public uint dwMaxTxQueue;
///
/// The maximum size of the driver's internal input buffer, in bytes. A value of zero indicates that no maximum value is imposed
/// by the serial provider.
///
public uint dwMaxRxQueue;
///
/// The maximum allowable baud rate, in bits per second (bps). This member can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// BAUD_0750x00000001
/// 75 bps
///
/// -
/// BAUD_1100x00000002
/// 110 bps
///
/// -
/// BAUD_134_50x00000004
/// 134.5 bps
///
/// -
/// BAUD_1500x00000008
/// 150 bps
///
/// -
/// BAUD_3000x00000010
/// 300 bps
///
/// -
/// BAUD_6000x00000020
/// 600 bps
///
/// -
/// BAUD_12000x00000040
/// 1200 bps
///
/// -
/// BAUD_18000x00000080
/// 1800 bps
///
/// -
/// BAUD_24000x00000100
/// 2400 bps
///
/// -
/// BAUD_48000x00000200
/// 4800 bps
///
/// -
/// BAUD_72000x00000400
/// 7200 bps
///
/// -
/// BAUD_96000x00000800
/// 9600 bps
///
/// -
/// BAUD_144000x00001000
/// 14400 bps
///
/// -
/// BAUD_192000x00002000
/// 19200 bps
///
/// -
/// BAUD_384000x00004000
/// 38400 bps
///
/// -
/// BAUD_56K0x00008000
/// 56K bps
///
/// -
/// BAUD_576000x00040000
/// 57600 bps
///
/// -
/// BAUD_1152000x00020000
/// 115200 bps
///
/// -
/// BAUD_128K0x00010000
/// 128K bps
///
/// -
/// BAUD_USER0x10000000
/// Programmable baud rate.
///
///
///
///
public uint dwMaxBaud;
///
/// The communications-provider type.
///
///
///
/// Value
/// Meaning
///
/// -
/// PST_FAX0x00000021
/// FAX device
///
/// -
/// PST_LAT0x00000101
/// LAT protocol
///
/// -
/// PST_MODEM0x00000006
/// Modem device
///
/// -
/// PST_NETWORK_BRIDGE0x00000100
/// Unspecified network bridge
///
/// -
/// PST_PARALLELPORT0x00000002
/// Parallel port
///
/// -
/// PST_RS2320x00000001
/// RS-232 serial port
///
/// -
/// PST_RS4220x00000003
/// RS-422 port
///
/// -
/// PST_RS4230x00000004
/// RS-423 port
///
/// -
/// PST_RS4490x00000005
/// RS-449 port
///
/// -
/// PST_SCANNER0x00000022
/// Scanner device
///
/// -
/// PST_TCPIP_TELNET0x00000102
/// TCP/IP Telnet protocol
///
/// -
/// PST_UNSPECIFIED0x00000000
/// Unspecified
///
/// -
/// PST_X250x00000103
/// X.25 standards
///
///
///
///
public PROV_SUB_TYPE dwProvSubType;
///
/// A bitmask indicating the capabilities offered by the provider. This member can be a combination of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// PCF_16BITMODE0x0200
/// Special 16-bit mode supported
///
/// -
/// PCF_DTRDSR0x0001
/// DTR (data-terminal-ready)/DSR (data-set-ready) supported
///
/// -
/// PCF_INTTIMEOUTS0x0080
/// Interval time-outs supported
///
/// -
/// PCF_PARITY_CHECK0x0008
/// Parity checking supported
///
/// -
/// PCF_RLSD0x0004
/// RLSD (receive-line-signal-detect) supported
///
/// -
/// PCF_RTSCTS0x0002
/// RTS (request-to-send)/CTS (clear-to-send) supported
///
/// -
/// PCF_SETXCHAR0x0020
/// Settable XON/XOFF supported
///
/// -
/// PCF_SPECIALCHARS0x0100
/// Special character support provided
///
/// -
/// PCF_TOTALTIMEOUTS0x0040
/// The total (elapsed) time-outs supported
///
/// -
/// PCF_XONXOFF0x0010
/// XON/XOFF flow control supported
///
///
///
///
public PROV_CAPABILITIES dwProvCapabilities;
///
///
/// A bitmask indicating the communications parameters that can be changed. This member can be a combination of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// SP_BAUD0x0002
/// Baud rate
///
/// -
/// SP_DATABITS0x0004
/// Data bits
///
/// -
/// SP_HANDSHAKING0x0010
/// Handshaking (flow control)
///
/// -
/// SP_PARITY0x0001
/// Parity
///
/// -
/// SP_PARITY_CHECK0x0020
/// Parity checking
///
/// -
/// SP_RLSD0x0040
/// RLSD (receive-line-signal-detect)
///
/// -
/// SP_STOPBITS0x0008
/// Stop bits
///
///
///
///
public COMM_SET_PARAMS dwSettableParams;
/// The baud rates that can be used. For values, see the dwMaxBaud member.
public uint dwSettableBaud;
///
/// A bitmask indicating the number of data bits that can be set. This member can be a combination of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// DATABITS_50x0001
/// 5 data bits
///
/// -
/// DATABITS_60x0002
/// 6 data bits
///
/// -
/// DATABITS_70x0004
/// 7 data bits
///
/// -
/// DATABITS_80x0008
/// 8 data bits
///
/// -
/// DATABITS_160x0010
/// 16 data bits
///
/// -
/// DATABITS_16X0x0020
/// Special wide path through serial hardware lines
///
///
///
///
public COMM_SET_DATA wSettableData;
///
///
/// A bitmask indicating the stop bit and parity settings that can be selected. This member can be a combination of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// STOPBITS_100x0001
/// 1 stop bit
///
/// -
/// STOPBITS_150x0002
/// 1.5 stop bits
///
/// -
/// STOPBITS_200x0004
/// 2 stop bits
///
/// -
/// PARITY_NONE0x0100
/// No parity
///
/// -
/// PARITY_ODD0x0200
/// Odd parity
///
/// -
/// PARITY_EVEN0x0400
/// Even parity
///
/// -
/// PARITY_MARK0x0800
/// Mark parity
///
/// -
/// PARITY_SPACE0x1000
/// Space parity
///
///
///
///
public COMM_STOP_PARITY wSettableStopParity;
/// The size of the driver's internal output buffer, in bytes. A value of zero indicates that the value is unavailable.
public uint dwCurrentTxQueue;
/// The size of the driver's internal input buffer, in bytes. A value of zero indicates that the value is unavailable.
public uint dwCurrentRxQueue;
///
///
/// Any provider-specific data. Applications should ignore this member unless they have detailed information about the format of
/// the data required by the provider.
///
///
/// Set this member to COMMPROP_INITIALIZED before calling the GetCommProperties function to indicate that the
/// wPacketLength member is already valid.
///
///
public uint dwProvSpec1;
///
/// Any provider-specific data. Applications should ignore this member unless they have detailed information about the format of
/// the data required by the provider.
///
public uint dwProvSpec2;
///
/// Any provider-specific data. Applications should ignore this member unless they have detailed information about the format of
/// the data required by the provider.
///
public IntPtr wcProvChar;
}
///
/// Contains the time-out parameters for a communications device. The parameters determine the behavior of ReadFile,
/// WriteFile, ReadFileEx, and WriteFileEx operations on the device.
///
// typedef struct _COMMTIMEOUTS { DWORD ReadIntervalTimeout; DWORD ReadTotalTimeoutMultiplier; DWORD ReadTotalTimeoutConstant; DWORD
// WriteTotalTimeoutMultiplier; DWORD WriteTotalTimeoutConstant;} COMMTIMEOUTS, *LPCOMMTIMEOUTS; https://msdn.microsoft.com/en-us/library/windows/desktop/aa363190(v=vs.85).aspx
[PInvokeData("Winbase.h", MSDNShortId = "aa363190")]
[StructLayout(LayoutKind.Sequential)]
public struct COMMTIMEOUTS
{
///
///
/// The maximum time allowed to elapse before the arrival of the next byte on the communications line, in milliseconds. If the
/// interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any
/// buffered data is returned. A value of zero indicates that interval time-outs are not used.
///
///
/// A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and
/// ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the bytes that
/// have already been received, even if no bytes have been received.
///
///
public uint ReadIntervalTimeout;
///
/// The multiplier used to calculate the total time-out period for read operations, in milliseconds. For each read operation,
/// this value is multiplied by the requested number of bytes to be read.
///
public uint ReadTotalTimeoutMultiplier;
///
///
/// A constant used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this
/// value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.
///
///
/// A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that
/// total time-outs are not used for read operations.
///
///
public uint ReadTotalTimeoutConstant;
///
/// The multiplier used to calculate the total time-out period for write operations, in milliseconds. For each write operation,
/// this value is multiplied by the number of bytes to be written.
///
public uint WriteTotalTimeoutMultiplier;
///
///
/// A constant used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this
/// value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written.
///
///
/// A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that
/// total time-outs are not used for write operations.
///
///
public uint WriteTotalTimeoutConstant;
}
/// Contains information about a communications device. This structure is filled by the ClearCommError function.
// typedef struct _COMSTAT { DWORD fCtsHold :1; DWORD fDsrHold :1; DWORD fRlsdHold :1; DWORD fXoffHold :1; DWORD fXoffSent :1; DWORD
// fEof :1; DWORD fTxim :1; DWORD fReserved :25; DWORD cbInQue; DWORD cbOutQue;} COMSTAT, *LPCOMSTAT; https://msdn.microsoft.com/en-us/library/windows/desktop/aa363200(v=vs.85).aspx
[PInvokeData("Winbase.h", MSDNShortId = "aa363200")]
[StructLayout(LayoutKind.Sequential)]
public struct COMSTAT
{
private uint bitvector1;
/// The number of bytes received by the serial provider but not yet read by a ReadFile operation.
public uint cbInQue;
///
/// The number of bytes of user data remaining to be transmitted for all write operations. This value will be zero for a
/// nonoverlapped write.
///
public uint cbOutQue;
/// If this member is TRUE, transmission is waiting for the CTS (clear-to-send) signal to be sent.
public bool fCtsHold { get => GetFlag(0x0001); set => SetFlag(0x0001, value); }
/// If this member is TRUE, transmission is waiting for the DSR (data-set-ready) signal to be sent.
public bool fDsrHold { get => GetFlag(0x0002); set => SetFlag(0x0002, value); }
///
/// If this member is TRUE, transmission is waiting for the RLSD (receive-line-signal-detect) signal to be sent.
///
public bool fRlsdHold { get => GetFlag(0x0004); set => SetFlag(0x0004, value); }
/// If this member is TRUE, transmission is waiting because the XOFF character was received.
public bool fXoffHold { get => GetFlag(0x0008); set => SetFlag(0x0008, value); }
///
/// If this member is TRUE, transmission is waiting because the XOFF character was transmitted. (Transmission halts when
/// the XOFF character is transmitted to a system that takes the next character as XON, regardless of the actual character.)
///
public bool fXoffSent { get => GetFlag(0x0010); set => SetFlag(0x0010, value); }
/// If this member is TRUE, the end-of-file (EOF) character has been received.
public bool fEof { get => GetFlag(0x0020); set => SetFlag(0x0020, value); }
///
/// If this member is TRUE, there is a character queued for transmission that has come to the communications device by way
/// of the TransmitCommChar function. The communications device transmits such a character ahead of other characters in
/// the device's output buffer.
///
public bool fTxim { get => GetFlag(0x0040); set => SetFlag(0x0040, value); }
private bool GetFlag(uint mask) => (bitvector1 & mask) != 0;
private void SetFlag(uint mask, bool value)
{
if (value) bitvector1 |= mask; else bitvector1 &= ~mask;
}
}
/// Defines the control setting for a serial communications device.
// typedef struct _DCB { DWORD DCBlength; DWORD BaudRate; DWORD fBinary :1; DWORD fParity :1; DWORD fOutxCtsFlow :1; DWORD
// fOutxDsrFlow :1; DWORD fDtrControl :2; DWORD fDsrSensitivity :1; DWORD fTXContinueOnXoff :1; DWORD fOutX :1; DWORD fInX :1; DWORD
// fErrorChar :1; DWORD fNull :1; DWORD fRtsControl :2; DWORD fAbortOnError :1; DWORD fDummy2 :17; WORD wReserved; WORD XonLim; WORD
// XoffLim; BYTE ByteSize; BYTE Parity; BYTE StopBits; char XonChar; char XoffChar; char ErrorChar; char EofChar; char EvtChar; WORD
// wReserved1;} DCB, *LPDCB; https://msdn.microsoft.com/en-us/library/windows/desktop/aa363214(v=vs.85).aspx
[PInvokeData("Winbase.h", MSDNShortId = "aa363214")]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DCB
{
/// The length of the structure, in bytes. The caller must set this member to .
public uint DCBlength;
///
///
/// The baud rate at which the communications device operates. This member can be an actual baud rate value, or one of the
/// following indexes.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// CBR_110110
/// 110 bps
///
/// -
/// CBR_300300
/// 300 bps
///
/// -
/// CBR_600600
/// 600 bps
///
/// -
/// CBR_12001200
/// 1200 bps
///
/// -
/// CBR_24002400
/// 2400 bps
///
/// -
/// CBR_48004800
/// 4800 bps
///
/// -
/// CBR_96009600
/// 9600 bps
///
/// -
/// CBR_1440014400
/// 14400 bps
///
/// -
/// CBR_1920019200
/// 19200 bps
///
/// -
/// CBR_3840038400
/// 38400 bps
///
/// -
/// CBR_5760057600
/// 57600 bps
///
/// -
/// CBR_115200115200
/// 115200 bps
///
/// -
/// CBR_128000128000
/// 128000 bps
///
/// -
/// CBR_256000256000
/// 256000 bps
///
///
///
///
public uint BaudRate;
private uint flags;
/// Reserved; must be zero.
public ushort wReserved;
///
/// The minimum number of bytes in use allowed in the input buffer before flow control is activated to allow transmission by the
/// sender. This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in the fInX,
/// fRtsControl, or fDtrControl members.
///
public ushort XonLim;
///
/// The minimum number of free bytes allowed in the input buffer before flow control is activated to inhibit the sender. Note
/// that the sender may transmit characters after the flow control signal has been activated, so this value should never be zero.
/// This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in the fInX, fRtsControl, or
/// fDtrControl members. The maximum number of bytes in use allowed is calculated by subtracting this value from the size,
/// in bytes, of the input buffer.
///
public ushort XoffLim;
/// The number of bits in the bytes transmitted and received.
public byte ByteSize;
///
/// The parity scheme to be used. This member can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// EVENPARITY2
/// Even parity.
///
/// -
/// MARKPARITY3
/// Mark parity.
///
/// -
/// NOPARITY0
/// No parity.
///
/// -
/// ODDPARITY1
/// Odd parity.
///
/// -
/// SPACEPARITY4
/// Space parity.
///
///
///
///
public Parity Parity;
///
/// The number of stop bits to be used. This member can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// ONESTOPBIT0
/// 1 stop bit.
///
/// -
/// ONE5STOPBITS1
/// 1.5 stop bits.
///
/// -
/// TWOSTOPBITS2
/// 2 stop bits.
///
///
///
///
public StopBits StopBits;
/// The value of the XON character for both transmission and reception.
public sbyte XonChar;
/// The value of the XOFF character for both transmission and reception.
public sbyte XoffChar;
/// The value of the character used to replace bytes received with a parity error.
public sbyte ErrorChar;
/// The value of the character used to signal the end of data.
public sbyte EofChar;
/// The value of the character used to signal an event.
public sbyte EvtChar;
/// Reserved; do not use.
public ushort wReserved1;
///
/// If this member is TRUE, binary mode is enabled. Windows does not support nonbinary mode transfers, so this member must
/// be TRUE.
///
public bool fBinary { get => GetFlag(0x01); set => SetFlag(0x01, value); }
/// If this member is TRUE, parity checking is performed and errors are reported.
public bool fParity { get => GetFlag(0x02); set => SetFlag(0x02, value); }
///
/// If this member is TRUE, the CTS (clear-to-send) signal is monitored for output flow control. If this member is
/// TRUE and CTS is turned off, output is suspended until CTS is sent again.
///
public bool fOutxCtsFlow { get => GetFlag(0x04); set => SetFlag(0x04, value); }
///
/// If this member is TRUE, the DSR (data-set-ready) signal is monitored for output flow control. If this member is
/// TRUE and DSR is turned off, output is suspended until DSR is sent again.
///
public bool fOutxDsrFlow { get => GetFlag(0x08); set => SetFlag(0x08, value); }
///
/// The DTR (data-terminal-ready) flow control. This member can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// DTR_CONTROL_DISABLE0x00
/// Disables the DTR line when the device is opened and leaves it disabled.
///
/// -
/// DTR_CONTROL_ENABLE0x01
/// Enables the DTR line when the device is opened and leaves it on.
///
/// -
/// DTR_CONTROL_HANDSHAKE0x02
///
/// Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the
/// EscapeCommFunction function.
///
///
///
///
///
public DTR_CONTROL fDtrControl { get => (DTR_CONTROL)((flags & 0x30) >> 4); set { flags = (flags & ~0x30U) | (((uint)value) << 4); } }
///
/// If this member is TRUE, the communications driver is sensitive to the state of the DSR signal. The driver ignores any
/// bytes received, unless the DSR modem input line is high.
///
public bool fDsrSensitivity { get => GetFlag(0x40); set => SetFlag(0x40, value); }
///
/// If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being
/// full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE,
/// transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has
/// transmitted the XonChar character to resume reception.
///
public bool fTXContinueOnXoff { get => GetFlag(0x80); set => SetFlag(0x80, value); }
///
/// Indicates whether XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when
/// the XoffChar character is received and starts again when the XonChar character is received.
///
public bool fOutX { get => GetFlag(0x100); set => SetFlag(0x100, value); }
///
/// Indicates whether XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar
/// character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is
/// sent when the input buffer comes within XonLim bytes of being empty.
///
public bool fInX { get => GetFlag(0x200); set => SetFlag(0x200, value); }
///
/// Indicates whether bytes received with parity errors are replaced with the character specified by the ErrorChar member.
/// If this member is TRUE and the fParity member is TRUE, replacement occurs.
///
public bool fErrorChar { get => GetFlag(0x400); set => SetFlag(0x400, value); }
/// If this member is TRUE, null bytes are discarded when received.
public bool fNull { get => GetFlag(0x800); set => SetFlag(0x800, value); }
///
/// The RTS (request-to-send) flow control. This member can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// RTS_CONTROL_DISABLE0x00
/// Disables the RTS line when the device is opened and leaves it disabled.
///
/// -
/// RTS_CONTROL_ENABLE0x01
/// Enables the RTS line when the device is opened and leaves it on.
///
/// -
/// RTS_CONTROL_HANDSHAKE0x02
///
/// Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than
/// one-half full and lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an
/// error for the application to adjust the line by using the EscapeCommFunction function.
///
///
/// -
/// RTS_CONTROL_TOGGLE0x03
///
/// Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent,
/// the RTS line will be low.
///
///
///
///
///
public RTS_CONTROL fRtsControl { get => (RTS_CONTROL)((flags & 0x3000) >> 12); set { flags = (flags & ~0x3000U) | (((uint)value) << 12); } }
///
/// If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs.
/// The driver will not accept any further communications operations until the application has acknowledged the error by calling
/// the ClearCommError function.
///
public bool fAbortOnError { get => GetFlag(0x4000); set => SetFlag(0x4000, value); }
private bool GetFlag(uint mask) => (flags & mask) != 0;
private void SetFlag(uint mask, bool value)
{
if (value) flags |= mask; else flags &= ~mask;
}
/// Gets a default instance with the size field set.
public static readonly DCB Default = new DCB { DCBlength = (uint)Marshal.SizeOf(typeof(DCB)) };
}
}
}