📄 commport.cs
字号:
using System;
using System.Runtime.InteropServices;
/// <summary>
/// commport 的摘要说明。
/// </summary>
namespace WindowsApplication2
{
public class CommPort
{
public int PortNum;
public int BaudRate;
public byte ByteSize;
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;
public int intcount=1;
// System.Collections.ArrayList allList = new System.Collections.ArrayList();
//comm port win32 file handle
private int hComm = -1;
public bool Opened = false;
//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;
~CommPort()
{
}
[StructLayout(LayoutKind.Sequential)] private struct DCB
{
public int DCBlength;
public int BaudRate;
public int Bits1;
public Int16 wReserved;
public Int16 XonLim;
public Int16 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 Int16 wReserved2;
}
[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 struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[StructLayout(LayoutKind.Sequential)]
public struct COMSTAT
{
public int fCtsHold;
public int fDsrHold;
public int fRlsdHold;
public int DWORD;
public int fXoffHold;
public int fXoffSent;
public int fEof;
public int fTxim;
public int fReserved;
public int cbInQue;
public int cbOutQue;
}
[DllImport("kernel32.dll")]
public static extern int ClearCommError(
int hFile,
ref uint lpError,
ref COMSTAT lpComstat
);
[DllImport("kernel32.dll")]
public 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
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // handle to communications device
[In] ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
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
);
[DllImport("kernel32.dll")]
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
);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
public void Open()
{
try
{
this.Opened = false;
DCB dcbCommPort = new DCB();
dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
/*dcbCommPort.XoffLim=50;
dcbCommPort.XonLim=50;
dcbCommPort.XonChar = (char)17;
dcbCommPort.XoffChar = (char)19;
*/
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if (hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("Comm Port Can Not Be Opened"));
}
// SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);
// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
//dcbCommPort.flags=0;
//dcb.fBinary=1;
//dcbCommPort.flags|=1;
dcbCommPort.Bits1 = 21393;
if (Parity>0)
{
//dcb.fParity=1
//dcbCommPort.flags|=2;
}
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
if (!SetCommState(hComm, ref dcbCommPort))
{
//uint ErrorNum=GetLastError();
//throw(new ApplicationException("can not open specific port!"));
}
//unremark to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
//GetCommState(hComm, ref dcbCommPort);
//why error??? why can i get 21393???
Opened = true;
}
catch (Exception ee)
{
throw new Exception("fail in opening port:" + ee.Message);
}
}
public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
Opened=false;
}
}
public byte[] Read(int NumBytes)
{
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
COMSTAT stat = new COMSTAT();
uint Error=0;
ClearCommError(hComm,ref Error,ref stat);
OutBytes = new byte[0];
if(stat.fDsrHold>0)
{
ReadFile(hComm,BufBytes,stat.fDsrHold,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
// System.Diagnostics.Debug.WriteLine("byte------"+this.intcount++);
}
else
{
throw(new ApplicationException("port is not open!"));
}
return OutBytes;
}
public void Write(byte[] WriteBytes)
{
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else
{
throw(new ApplicationException("port is not open!"));
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -