我想从串口捕获信息,是不是通过mscomm来解决。
我通过网上找到一个串口类,可是执行到读的位置就陷进去了,cpu长到100%,一直处于等待状态,
在hCommRead=ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort); 这个位置
总的代码:
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CommLib
{
/// <summary>
/// SerialPort 的摘要说明。
/// </summary>
public class SerialPort : System.ComponentModel.Component
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public SerialPort(System.ComponentModel.IContainer container)
{
/// <summary>
/// Windows.Forms 类撰写设计器支持所必需的
/// </summary>
container.Add(this);
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} public SerialPort()
{
/// <summary>
/// Windows.Forms 类撰写设计器支持所必需的
/// </summary>
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
PortNum = "COM1:"; // 1 端口号
BaudRate = 9600; // 9600 波特率
ByteSize = 8; // 8位 数据位
Parity = 0; // 0-4=no,odd,even,,space 校验位
StopBits = 1; // 0,1,2 = 1, 1.5, 2 停止位
}
我通过网上找到一个串口类,可是执行到读的位置就陷进去了,cpu长到100%,一直处于等待状态,
在hCommRead=ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort); 这个位置
总的代码:
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CommLib
{
/// <summary>
/// SerialPort 的摘要说明。
/// </summary>
public class SerialPort : System.ComponentModel.Component
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public SerialPort(System.ComponentModel.IContainer container)
{
/// <summary>
/// Windows.Forms 类撰写设计器支持所必需的
/// </summary>
container.Add(this);
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} public SerialPort()
{
/// <summary>
/// Windows.Forms 类撰写设计器支持所必需的
/// </summary>
InitializeComponent(); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
PortNum = "COM1:"; // 1 端口号
BaudRate = 9600; // 9600 波特率
ByteSize = 8; // 8位 数据位
Parity = 0; // 0-4=no,odd,even,,space 校验位
StopBits = 1; // 0,1,2 = 1, 1.5, 2 停止位
}
//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;
[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
public int fDtrControl; // DTR flow control type
public int fDsrSensitivity; // DSR sensitivity
public int fTXContinueOnXoff; // XOFF continues Tx
public 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,,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 EofChar; // 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 struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[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
);
[DllImport("kernel32")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
[DllImport("kernel32")]
private static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[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
);
[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
);
[DllImport("kernel32")]
private static extern bool CloseHandle(
int hObject // handle to object
); #endregion
#region 属性
public string PortNum; // 1 端口号
public int BaudRate; // 9600 波特率
public byte ByteSize; // 8位 数据位
public byte Parity; // 0-4=no,odd,even,,space 校验位
public byte StopBits; // 0,1,2 = 1, 1.5, 2 停止位
public int ReadTimeout; // 读超时
public int InitOK;
//comm port win32 file handle
public int hComm = -1;
public bool hCommRead = false;
public bool Opened = false; //写入和读出数据缓冲
public byte[] InByteData; //发送数据
public byte[] OutByteData; //读入数据
#endregion /// <summary>
///串口的初始化函数
///lpFileName 端口名
///baudRate 波特率
///parity 校验位
/// <summary>
public bool PortInitialize(string lpFileName,int baudRate,byte parity)
{
//保存端口设置
try
{
PortNum = lpFileName;
BaudRate = baudRate;
Parity = parity;
InitOK = 1;
}
catch
{
InitOK = 0;
}
//打开端口
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile(lpFileName ,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("串口打开不成功"));
//return false;
}
// 设置通信超时时间 SET THE COMM TIMEOUTS
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.
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);
Opened = true;
return true;
}
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
}
}
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("串口没有打开!"));
}
}
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;
hCommRead=ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("串口没有打开!"));
}
return OutBytes;
}
#region Component Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}
用这个,好用
http://msdn.microsoft.com/msdnmag/issues/02/10/NETSerialComm/default.aspx