usingSystem;usingSystem.Runtime.InteropServices;
namespaceNativeDll{///<summary>///SerialPort的摘要说明。///</summary>publicclassSerialPort{#region申明要引用的和串口调用有关的API//win32apiconstantsprivateconstuintGENERIC_READ=0x80000000;privateconstuintGENERIC_WRITE=0x40000000;privateconstintOPEN_EXISTING=3; privateconstintINVALID_HANDLE_VALUE=-1;privateconstintMAXBLOCK=4096;
privateconstuintPURGE_TXABORT=0x0001; //Killthepending/currentwritestothecommport.privateconstuintPURGE_RXABORT=0x0002; //Killthepending/currentreadstothecommport.privateconstuintPURGE_TXCLEAR=0x0004; //Killthetransmitqueueifthere.privateconstuintPURGE_RXCLEAR=0x0008; //Killthetypeaheadbufferifthere.[StructLayout(LayoutKind.Sequential)]privatestructDCB {//takenfromcstructinplatformsdk publicintDCBlength; //sizeof(DCB) publicintBaudRate; //currentbaudrate publicintfBinary; //binarymode,noEOFcheck publicintfParity; //enableparitychecking publicintfOutxCtsFlow; //CTSoutputflowcontrol publicintfOutxDsrFlow; //DSRoutputflowcontrol publicintfDtrControl; //DTRflowcontroltype publicintfDsrSensitivity; //DSRsensitivity publicintfTXContinueOnXoff;//XOFFcontinuesTx publicintfOutX; //XON/XOFFoutflowcontrol publicintfInX; //XON/XOFFinflowcontrol publicintfErrorChar; //enableerrorreplacement publicintfNull; //enablenullstripping publicintfRtsControl; //RTSflowcontrol publicintfAbortOnError; //abortonerror publicintfDummy2; //reserved publicushortwReserved; //notcurrentlyused publicushortXonLim; //transmitXONthreshold publicushortXoffLim; //transmitXOFFthreshold publicbyteByteSize; //numberofbits/byte,4-8 publicbyteParity; //0-4=no,odd,even,mark,space publicbyteStoPBits; //0,1,2=1,1.5,2 publiccharXonChar; //TxandRxXONcharacter publiccharXoffChar; //TxandRxXOFFcharacter publiccharErrorChar; //errorreplacementcharacter publiccharEofChar; //endofinputcharacter publiccharEvtChar; //receivedeventcharacter publicushortwReserved1; //reserved;donotuse }
[StructLayout(LayoutKind.Sequential)]privatestructCOMMTIMEOUTS { publicintReadIntervalTimeout; publicintReadTotalTimeoutMultiplier; publicintReadTotalTimeoutConstant; publicintWriteTotalTimeoutMultiplier; publicintWriteTotalTimeoutConstant; }
[StructLayout(LayoutKind.Sequential)] privatestructOVERLAPPED { publicint Internal; publicint InternalHigh; publicint Offset; publicint OffsetHigh; publicinthEvent; }
[StructLayout(LayoutKind.Sequential)]privatestructCOMSTAT{/*publicintfCtsHold;publicintfDsrHold;publicintfRlsdHold;publicintfXoffHold;publicintfXoffSent;publicintfEof;publicintfTxim;publicintfReserved;publicintcbInQue;publicintcbOutQue;*///Shouldhaveareverse,idon'tknowwhy!!!!!publicintcbOutQue;publicintcbInQue;publicintfReserved;publicintfTxim;publicintfEof;publicintfXoffSent;publicintfXoffHold;publicintfRlsdHold;publicintfDsrHold;publicintfCtsHold; }#ifFULLFramework[DllImport("kernel32")]privatestaticexternintCreateFile(stringlpFileName, //filenameuintdwDesiredAccess, //accessmodeintdwShareMode, //sharemodeintlpSecurityAttributes,//SDintdwCreationDisposition, //howtocreateintdwFlagsAndAttributes, //fileattributesinthTemplateFile //handletotemplatefile http://www.mscto.com );#else[DllImport("coredll")]privatestaticexternintCreateFile(stringlpFileName, //filenameuintdwDesiredAccess, //accessmodeintdwShareMode, //sharemodeintlpSecurityAttributes,//SDintdwCreationDisposition, //howtocreateintdwFlagsAndAttributes, //fileattributesinthTemplateFile //handletotemplatefile);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolGetCommState(inthFile, //handletocommunicationsdevicerefDCBlpDCB //device-controlblock); #else[DllImport("coredll")]privatestaticexternboolGetCommState(inthFile, //handletocommunicationsdevicerefDCBlpDCB //device-controlblock);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolBuildCommDCB(stringlpDef, //device-controlstringrefDCBlpDCB //device-controlblock
);#else[DllImport("coredll")]privatestaticexternboolBuildCommDCB(stringlpDef, //device-controlstringrefDCBlpDCB //device-controlblock);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolSetCommState(inthFile, //handletocommunicationsdevicerefDCBlpDCB //device-controlblock);#else[DllImport("coredll")]privatestaticexternboolSetCommState(inthFile, //handletocommunicationsdevicerefDCBlpDCB //device-controlblock);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolGetCommTimeouts(inthFile, //handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts //time-outvalues);#else[DllImport("coredll")]privatestaticexternboolGetCommTimeouts(inthFile, //handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts //time-outvalues);#endif#ifFULLFRAMEWORK[DllImport("kernel32")] privatestaticexternboolSetCommTimeouts(inthFile, //handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts //time-outvalues);#else[DllImport("coredll")] privatestaticexternboolSetCommTimeouts(inthFile, //handletocommdevicerefCOMMTIMEOUTSlpCommTimeouts //time-outvalues);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolReadFile(inthFile, //handletofilebyte[]lpBuffer, //databufferintnNumberOfBytesToRead, //numberofbytestoreadrefintlpNumberOfBytesRead,//numberofbytesreadrefOVERLAPPEDlpOverlapped //overlappedbuffer);#else[DllImport("coredll")]privatestaticexternboolReadFile(inthFile, //handletofilebyte[]lpBuffer, //databufferintnNumberOfBytesToRead, //numberofbytestoreadrefintlpNumberOfBytesRead,//numberofbytesread refOVERLAPPEDlpOverlapped //overlappedbuffer);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolWriteFile(inthFile, //handletofilebyte[]lpBuffer, //databufferintnNumberOfBytesToWrite, //numberofbytestowriterefintlpNumberOfBytesWritten, //numberofbyteswrittenrefOVERLAPPEDlpOverlapped //overlappedbuffer);#else[DllImport("coredll")]privatestaticexternboolWriteFile(inthFile, //handletofilebyte[]lpBuffer, //databufferintnNumberOfBytesToWrite, //numberofbytestowriterefintlpNumberOfBytesWritten, //numberofbyteswrittenrefOVERLAPPEDlpOverlapped //overlappedbuffer);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolCloseHandle(inthObject //handletoobject);#else[DllImport("coredll")]privatestaticexternboolCloseHandle(inthObject //handletoobject 软件开发网 );#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolClearCommError(inthFile, //handletofilerefintlpErrors,refCOMSTATlpStat);#else[DllImport("coredll")]privatestaticexternboolClearCommError(inthFile, //handletofilerefintlpErrors,refCOMSTATlpStat);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolPurgeComm(inthFile, //handletofileuintdwFlags);#else[DllImport("coredll")]privatestaticexternboolPurgeComm(inthFile, //handletofileuintdwFlags);#endif#ifFULLFRAMEWORK[DllImport("kernel32")]privatestaticexternboolSetupComm(inthFile,intdwInQueue,intdwOutQueue);#else[DllImport("coredll")]privatestaticexternboolSetupComm(inthFile,intdwInQueue,intdwOutQueue);#endif#endregion
//SerialPort的成员变量privateinthComm=INVALID_HANDLE_VALUE;privateboolbOpened=false;
publicboolOpened{get{returnbOpened;}}///<summary>///串口的初始化函数///lpFileName 端口名///baudRate 波特率///parity 校验位///byteSize 数据位///stopBits 停止位///<summary>public boolOpenPort(stringlpFileName,intbaudRate,byteparity,bytebyteSize,bytestopBits) { //OPENTHECOMMPORT. hComm=CreateFile(lpFileName,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);//IFTHEPORTCANNOTBEOPENED,BAILOUT.if(hComm==INVALID_HANDLE_VALUE) {returnfalse;}
SetupComm(hComm,MAXBLOCK,MAXBLOCK);//SETTHECOMMTIMEOUTS.COMMTIMEOUTSctoCommPort=newCOMMTIMEOUTS();GetCommTimeouts(hComm,refctoCommPort);ctoCommPort.ReadIntervalTimeout=Int32.MaxValue;ctoCommPort.ReadTotalTimeoutConstant=0;ctoCommPort.ReadTotalTimeoutMultiplier=0;ctoCommPort.WriteTotalTimeoutMultiplier=10;ctoCommPort.WriteTotalTimeoutConstant=1000; SetCommTimeouts(hComm,refctoCommPort);//SETBAUDRATE,PARITY,WORDSIZE,ANDSTOPBITS.//THEREAREOTHERWAYSOFDOINGSETTINGTHESEBUTTHISISTHEEASIEST.//IFYOUWANTTOLATERADDCODEFOROTHERBAUDRATES,REMEMBER//THATTHEARGUMENTFORBuildCommDCBMUSTBEAPOINTERTOASTRING.//ALSONOTETHATBuildCommDCB()DEFAULTSTONOHANDSHAKING.DCBdcbCommPort=newDCB();dcbCommPort.DCBlength=Marshal.SizeOf(dcbCommPort);GetCommState(hComm,refdcbCommPort);dcbCommPort.BaudRate=baudRate;dcbCommPort.Parity=parity;dcbCommPort.ByteSize=byteSize;dcbCommPort.StopBits=stopBits; SetCommState(hComm,refdcbCommPort);
PurgeComm(hComm,PURGE_RXCLEAR|PURGE_RXABORT);PurgeComm(hComm,PURGE_TXCLEAR|PURGE_TXABORT);bOpened=true;returntrue;}
//关闭串口publicboolClosePort() {if(hComm==INVALID_HANDLE_VALUE) {returnfalse;}if(CloseHandle(hComm)){hComm=INVALID_HANDLE_VALUE;bOpened=false;returntrue;}else{returnfalse;}}
//往串口写数据publicboolWritePort(byte[]WriteBytes) {if(hComm==INVALID_HANDLE_VALUE) {returnfalse;}
COMSTATComStat=newCOMSTAT();intdwErrorFlags=0;
ClearCommError(hComm,refdwErrorFlags,refComStat);if(dwErrorFlags!=0)PurgeComm(hComm,PURGE_TXCLEAR|PURGE_TXABORT); 软件开发网
OVERLAPPEDovlCommPort=newOVERLAPPED();intBytesWritten=0;returnWriteFile(hComm,WriteBytes,WriteBytes.Length,refBytesWritten,refovlCommPort); }//从串口读数据publicboolReadPort(intNumBytes,refbyte[]commRead) {if(hComm==INVALID_HANDLE_VALUE) {returnfalse;}COMSTATComStat=newCOMSTAT();intdwErrorFlags=0;ClearCommError(hComm,refdwErrorFlags,refComStat);if(dwErrorFlags!=0)PurgeComm(hComm,PURGE_RXCLEAR|PURGE_RXABORT);if(ComStat.cbInQue>0){OVERLAPPEDovlCommPort=newOVERLAPPED();intBytesRead=0;returnReadFile(hComm,commRead,NumBytes,refBytesRead,refovlCommPort);}else{returnfalse;}}}}