C # packages a serial operation class (available for Win CE)

xiaoxiao2021-03-06  41

Using system; using system.runtime.interopservices;

Namespace Native NativeDLL {///

/// SerialPort's summary description. /// public class SerialPort {#region affirmed and serial API calls related to reference // win32 api constants private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const int OPEN_EXISTING = 3; private Const int invalid_handle_value = -1; private const Int maxblock = 4096;

private const uint PURGE_TXABORT = 0x0001; // Kill the pending / current writes to the comm port private const uint PURGE_RXABORT = 0x0002;. // Kill the pending / current reads to the comm port private const uint PURGE_TXCLEAR = 0x0004;. // Kill . the transmit queue if there private const uint PURGE_RXCLEAR = 0x0008;. // Kill the typeahead buffer if there [StructLayout (LayoutKind.Sequential)] private struct DCB {// taken from c struct in platform sdk public int DCBlength; // sizeof (DCB) public int BaudRate; // current baud rate public int fBinary; // binary mode, no EOF check public int fParity; // enable parity checking public int fOutxCtsFlow; // CTS output flow control public int fOutxDsrFlow; // DSR Output Flow Control; // DTR Flow Control Type Public Int Fdsrsensitivity; // DSR Sensitivity Public Int ftxContinueonxoff; // Xoff Continues TX PUBL ic int fOutX; // XON / XOFF out flow control public int fInX; // XON / XOFF in flow control public int fErrorChar; // enable error replacement public int fNull; // enable null stripping public int fRtsControl; // RTS flow control public int fAbortOnError; // abort on error public int fDummy2; // reserved public ushort wReserved; // not currently used public ushort XonLim; // transmit XON threshold public ushort XoffLim; // transmit XOFF threshold public byte ByteSize; // Number of Bits / Byte, 4-8 Public Byte Parity; // 0-4 = NO, ODD, Even, Mark, Space Public Byte Stopbits

// 0, 1, 2 = 1, 1.5, 2 public char xonchar; // TX and RX XON Character public char Xoffchar; // tx and rx xoff character public char errorchar; // error Replacement Character public char eofcha; //// end of input character public char EvtChar; // received event character public ushort wReserved1; // reserved; do not use} [StructLayout (LayoutKind.Sequential)] private struct COMMTIMEOUTS {public int ReadIntervalTimeout; public int ReadTotalTimeoutMultiplier; public int ReadTotalTimeoutConstant; public Int WriteTotalTimeOutmultiPlier; Public Int WriteTotalTimeoutConstant;

[StructLayout (layoutkind.sequential] private intert overlapped {public int interunalhigh; public int offset; public int

[StructLayout (LayoutKind.Sequential)] private struct COMSTAT {/ * public int fCtsHold; public int fDsrHold; public int fRlsdHold; public int fXoffHold; public int fXoffSent; public int fEof; public int fTxim; public int fReserved; public int cbInQue; public int cbOutQue; * / // Should have a reverse, i do not know why !!!!! public int cbOutQue; public int cbInQue; public int fReserved; public int fTxim; public int fEof; public int fXoffSent; public int fXoffHold; public int fRlsdHold; public int fDsrHold; public int fCtsHold;} #if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern int CreateFile (string lpFileName, // file name uint dwDesiredAccess, // access mode int dwShareMode, / / Share Mode int LPSecurityAttributes, // sd int dwcreationdisposition, // how to create int dwflagsandattributes, // file attributes int hTemplateFile // handle to template file); # else [DllImport ( "coredll")] private static extern int CreateFile (string lpFileName, // file name uint dwDesiredAccess, // access mode int dwShareMode, // share mode int lpSecurityAttributes, // sd dwcreationdisposition, // how to create int dwflagsandattributes, // file attribute to time); # Endif # if fullframework [DLLIMPORT ("kernel32"

)] Private static extern bool GetCommState (int hFile, // handle to communications device ref DCB lpDCB // device-control block); #else [DllImport ( "coredll")] private static extern bool GetCommState (int hFile, // handle to communications device ref DCB lpDCB // device-control block); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern bool BuildCommDCB (string lpDef, // device-control string ref DCB lpDCB // device-control block); #else [DllImport ( "coredll")] private static extern bool BuildCommDCB (string lpDef, // device-control string ref DCB lpDCB // device-control block); # endif # if FULLFRAMEWORK [DllImport ( "kernel32" )] private static extern bool SetCommState (int hFile, // handle to communications device ref DCB lpDCB // device-control block); # else [DllImport ( "coredll")] private static extern bool SetCommState (int hFile, // handle To Communications Device Ref DCB LPD CB // device-control block); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern bool GetCommTimeouts (int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values); # else [DllImport ( "coredll")] private static extern bool GetCommTimeouts (int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern Bool setcommtimeouts (int hfile, // handle to commit commick ref "lp); # else [DLLIMPORT (" Coredll "

)] Private static extern bool SetCommTimeouts (int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] 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); # else [DllImport ( "coredll ")] 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; # Endif # if fullframework [DLLIMPORT ("kernel32")] 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); #else [DllImport ( "coredll")] 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); # ENDIF # ix ifeframework [DLLIMPORT ("kernel32"

)] Private static extern bool CloseHandle (int hObject // handle to object); # else [DllImport ( "coredll")] private static extern bool CloseHandle (int hObject // handle to object); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern bool ClearCommError (int hFile, // handle to file ref int lpErrors, ref COMSTAT lpStat); # else [DllImport ( "coredll")] private static extern bool ClearCommError (int hFile, // handle to file ref int lpErrors, ref COMSTAT lpStat); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern bool PurgeComm (int hFile, // handle to file uint dwFlags); # else [DllImport ( "coredll" )] private static extern bool PurgeComm (int hFile, // handle to file uint dwFlags); # endif # if FULLFRAMEWORK [DllImport ( "kernel32")] private static extern bool SetupComm (int hFile, int dwInQueue, int dwOutQueue); # Else [DLLIMPORT ("Coredll")] Private Static Extern Bool SetupComm INT HFILE, INT DWINQUEUE, INT DWoutqueue); # Endif # endregion // SerialPort member Variable Private Int hcomm = invalid_handle_value; private bool bind = false;

Public Bool Opened;}} ///

/// serial port initialization function /// lpfilename port name /// baudRate baud rate /// Parity check /// BYtesize data bit /// stopBits stop bit /// public bool OpenPort (string lpFileName, int baudRate, byte parity, byte byteSize, byte stopBits) {// OPEN THE COMM PORT hComm = CreateFile (lpFileName, GENERIC_READ |. GENERIC_WRITE, 0 , 0, 0); // if the port cannot be opened, bail out. If (hcomm == invalid_handle_value) {Return False;} setupcomm (hcomm, maxblock, maxblock); // set the commit the communeouts. COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS (); GetCommTimeouts (hComm, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = Int32.MaxValue; ctoCommPort.ReadTotalTimeoutConstant = 0; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutConstant = 1000; 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 DCB dcbCommPort = new DCB ();. 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);

PurgeComm (hComm, PURGE_RXCLEAR | PURGE_RXABORT); PurgeComm (hComm, PURGE_TXCLEAR | PURGE_TXABORT); bOpened = true; return true;} // close the serial port public bool ClosePort () {if (hComm == INVALID_HANDLE_VALUE) {return false;} if ( CloseHandle (hcomm)) {hcomm = invalid_handle_value; bopENed = false; return true;} else {return false;}}

/ / Write data to serial port Writeport (byte [] Writebytes) {if (hcomm == invalid_handle_value) {Return False;}

COMSTAT COMSTAT = New Comst (); int dwerrorflags = 0;

Clearcommrror (HCOMM, REF DWERRORFLAGS, REF Comstat); if (dwerrorflags! = 0) purgecomm (hcomm, purge_txclear | purge_txabort);

OVERLAPPED ovlCommPort = new OVERLAPPED (); int BytesWritten = 0; return WriteFile (hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);} // read from the serial data public bool ReadPort (int NumBytes, ref byte [] commRead ) {If (hcomm == invalid_handle_value) {return false;} comStat Comstat = new comstat (); int dwerrorflags = 0;

ClearCommError (hComm, ref dwErrorFlags, ref ComStat); if (dwErrorFlags = 0!) PurgeComm (hComm, PURGE_RXCLEAR | PURGE_RXABORT); if (ComStat.cbInQue> 0) {OVERLAPPED ovlCommPort = new OVERLAPPED (); int BytesRead = 0; return Readfile (HCOMM, CommRead, Numbytes, Ref Bytesread, Ref ovlcommport);} else {returnaf false;}}}}

转载请注明原文地址:https://www.9cbs.com/read-60771.html

New Post(0)