希望有朋友与我联系!
EMail: [email protected]
EMail: [email protected]
解决方案 »
- 帮我看下用什么控件好
- C# 调用delphi DLL 问题。
- reportViewer显示RDLC报表时的问题
- CAB,泛型与typeof,编译出错,请高手指教!
- 为什么我的客户端程序内存只消耗,不释放
- ★★★★★【加分贴2】用webbrowser控件做一个资源管理器,如何得到IE控件中选中(鼠标多选)的文件名称列表?
- 超级急!!!在线等!!!!!如何在WINFORM程序中打开一个cvs文件,还有Access登陆权限问题
- 怎么让控件通过安全策略
- VS2005怎么开发出风格不一样的漂亮窗体?
- 怎样能实现mainmenu控件的设计器
- 关于VSS的问题
- 有谁做过像 88ip / 花生壳 这种可以解析动态IP的程序???
我看过下面的链接:
http://expert.csdn.net/Expert/topic/2771/2771718.xml?temp=.5443689
里面有一个例子不错,但是如何使用好呢?
还请帮忙!
我的分很多!散啦!
http://www.codeproject.com/dotnet/DotNetComPorts.asp
http://msdn.microsoft.com/msdnmag/issues/02/10/NETSerialComm/default.aspx
using System;
using System.Runtime.InteropServices;
using System.Xml;
namespace Dhthx.WinUI.Common
{
public abstract class CommPort
{
protected int PortNum;
protected int BaudRate;
protected byte ByteSize;
protected byte Parity; // 0-4=no,odd,even,,space
protected byte StopBits; // 0,1,2 = 1, 1.5, 2
protected int ReadTimeout;
//comm port win32 file handle
protected int hComm = -1;
protected bool Opened = false; /*********************************************************************************
* *
* 引用Win32 API *
* *
* *******************************************************************************/
protected const uint GENERIC_READ = 0x80000000;
protected const uint GENERIC_WRITE = 0x40000000;
protected const int OPEN_EXISTING = 3;
protected const int INVALID_HANDLE_VALUE = -1;
[StructLayout(LayoutKind.Sequential)]
protected struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // current baud rate
public uint flags;
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)]
protected struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
protected struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[DllImport("kernel32.dll")]
protected 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")]
protected static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
protected static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
protected static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
protected static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
protected static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
protected 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")]
protected 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")]
protected static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
protected static extern uint GetLastError(); [StructLayout( LayoutKind.Sequential )] protected struct COMSTAT
{
internal const uint fCtsHold = 0x1;
internal const uint fDsrHold = 0x2;
internal const uint fRlsdHold = 0x4;
internal const uint fXoffHold = 0x8;
internal const uint fXoffSent = 0x10;
internal const uint fEof = 0x20;
internal const uint fTxim = 0x40;
internal UInt32 Flags;
internal UInt32 cbInQue;
internal UInt32 cbOutQue;
}
[DllImport("kernel32.dll")]
protected static extern Boolean ClearCommError(int hFile, out UInt32 lpErrors, out COMSTAT cs);
[DllImport("kernel32.dll")]
protected static extern bool PurgeComm(int hFile,UInt32 dwFlags); protected const uint PURGE_TXABORT = 0x0001;
protected const uint PURGE_RXABORT = 0x0002;
protected const uint PURGE_TXCLEAR = 0x0004;
protected const uint PURGE_RXCLEAR = 0x0008;
* *
* *
* *
* 定义方法区域 *
* *
* *
* *
* ************************************************************************/
public abstract void Open();
public abstract string Read();
public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
}
}
public void ClearBuff()
{
PurgeComm(hComm,PURGE_RXCLEAR);
}
public CommPort()
{
try
{
string xmlname=System.Environment.CurrentDirectory+@"\config.xml";
XmlDocument xmldoc=new XmlDocument();
xmldoc.Load(xmlname);
string comid=xmldoc.DocumentElement.SelectSingleNode("COM/ComID").InnerText.Trim(); if (comid.Equals(""))
{
PortNum=1;
}
else
{
PortNum=Convert.ToInt32(comid);
}
string baud=xmldoc.DocumentElement.SelectSingleNode("COM/BaudRate").InnerText.Trim();
if (baud.Equals(""))
{
BaudRate=9600;
}
else
{
BaudRate=Convert.ToInt32(baud);
} string bytesize=xmldoc.DocumentElement.SelectSingleNode("COM/ByteSize").InnerText.Trim();
if (bytesize.Equals(""))
{
ByteSize=8;
}
else
{
ByteSize=Convert.ToByte(bytesize);
}
string parity=xmldoc.DocumentElement.SelectSingleNode("COM/Parity").InnerText.Trim();
if (parity.Equals(""))
{
Parity=0; // 0-4=no,odd,even,,space
}
else
{
Parity=Convert.ToByte(parity);
}
string stopBits=xmldoc.DocumentElement.SelectSingleNode("COM/StopBits").InnerText.Trim();
if (parity.Equals(""))
{
StopBits=0;
}
else
{
StopBits=Convert.ToByte(stopBits);
}
}
catch(Exception e)
{
throw new Exception("读取配置文件出错",e);
}
}
public string ByteToString(byte[] InBytes,int beginIndex,int length)
{
string stringOut="";
for(int i=0;i<length;i++)
{
stringOut=stringOut + String.Format("{0:X2}",InBytes[i+beginIndex]);
}
return stringOut;
}
public string AsciiToString(byte[] inBytes,int beginIndex,int length)
{
return System.Text.ASCIIEncoding.ASCII.GetString(inBytes,beginIndex,length);
}
public byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length-1];
for (int i = 0;i==ByteStrings.Length-1;i++)
{
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
public int ByteToInt(byte[] Inbytes,int beginIndex,int length)
{
byte[] bytes=new byte[length];
for(int i=0;i<length;i++)
{
bytes[i]=Inbytes[i+beginIndex];
}
int temp=0;
int card=0;
for(int i=0;i<length;i++)
{
temp=bytes[i];
for(int j=1;j<length-i;j++)
{
temp=temp*256;
}
card|=temp;
}
return card;
}
}
{
public CommPortOne():base()
{
}
public override void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile("COM"+PortNum.ToString(),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;
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("Comm Port Can Not Be Opened"));
}
//unre to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened=true;
}
public override string Read()
{
byte[] BufBytes;
byte[] OutBytes;
int NumBytes=11;
UInt32 dwError;
COMSTAT cs;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ClearCommError(hComm,out dwError,out cs);
if (cs.cbInQue==0)return "-1";
if (cs.cbInQue>NumBytes)
{
PurgeComm(hComm,PURGE_RXCLEAR);
return "-1";
}
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("Comm Port Not Open"));
}
return this.ByteToInt(OutBytes,6,4).ToString();
}
}
{ public CommPortTwo():base()
{
}
public override void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile("COM"+PortNum.ToString(),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;
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("Comm Port Can Not Be Opened"));
}
//unre to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened=true;
}
public override string Read()
{
byte[] BufBytes;
byte[] OutBytes;
int NumBytes=13;
UInt32 dwError;
COMSTAT cs;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ClearCommError(hComm,out dwError,out cs);
if (cs.cbInQue==0)return "-1";
if (cs.cbInQue>NumBytes)
{
PurgeComm(hComm,PURGE_RXCLEAR);
return "-1";
}
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("Comm Port Not Open"));
}
return this.AsciiToString(OutBytes,3,8);
}
}
public class ComAccess
{
private CommPort m_commport;
public ComAccess()
{
try
{
string xmlname=System.Environment.CurrentDirectory+@"\config.xml";
XmlDocument xmldoc=new XmlDocument();
xmldoc.Load(xmlname);
string comtype=xmldoc.DocumentElement.SelectSingleNode("COM/ComType").InnerText.Trim();
switch(comtype)
{
case "1":
{
m_commport=new CommPortOne();break;
}
case "2":
{
m_commport=new CommPortTwo();break;
}
default:
{
m_commport=new CommPortOne();break;
}
}
}
catch(Exception e)
{
throw new Exception("读取配置文件出错",e);
}
}
public string ReadData()
{
return m_commport.Read();
}
public void ExitComPort()
{
m_commport.Close();
}
public void InitComPort()
{
m_commport.Open();
}
public void ClearBuff()
{
m_commport.ClearBuff();
}
}
}
你的类在VS2003中,移动设备Pocket PC2003环境上调试出错!
Array.Copy(BufBytes,OutBytes,BytesRead);报错为没有参数3.
还有是CreateFile(....).不能通过!
有QQ吗!