自己写的 C++ 串口通讯类,希望大家帮忙指正!自己使用过,能行!但感觉非常不好。。。。。//---------------------
自己写的 C++ 串口通讯类,希望大家帮忙指正!自己使用过,能行!但感觉非常不好。。。。。
//---------------------------------------
#ifndef _MscommH_H
#define _MscommH_H
//---------------------------------------
#include <windows.h>
#include <stdio.h>
#include <string.h>
#defineWM_COMM_RXCHARWM_USER + 10 //自定义串口接收数据消息
class Mscomm
{
private:
HWNDwHand;//主窗口句柄
HANDLEhThread;//线程句柄
HANDLEhComm; //串口句柄
boolIsOpen;//记录串口是否打开
boolThreadFlag; //线程开关标记
OVERLAPPEDWriteovReady,ReadovReady; //读写异步结构,用来保存异步操作结果
//以 Delimit 为分隔符拆分字符串 Str 到字符数组 S 中
//voidSplitStr(String *S,String Str, char Delimit);
protected:
COMSTAT lpStat;
DWORD dwError;
DWORD GetInBufferCount()
{
dwError = 0;
lpStat.cbInQue = 0;
ClearCommError(hComm,&dwError,&lpStat);
return lpStat.cbInQue ;
}
voidSetInBufferCount(int InBuf)
{
if(!InBuf)
PurgeComm(hComm, PURGE_RXCLEAR);
}
DWORD GetOutBufferCount()
{
dwError = 0;
lpStat.cbOutQue = 0;
ClearCommError(hComm,&dwError,&lpStat);
return lpStat.cbOutQue ;
}
voidSetOutBufferCount(int OutBuf)
{
if(!OutBuf)
PurgeComm(hComm, PURGE_TXCLEAR);
}
voidSetRThreshold(bool RTh) //线程开启和挂起函数
{
if((!this->ThreadFlag) && RTh)
{
ResumeThread(hThread);
}
if(this->ThreadFlag && !RTh)
{
SuspendThread(hThread);
}
this->ThreadFlag = RTh;
}
//boolGetRThreshold(void){return ThreadFlag;}
/***********************线程函数**********************/
static DWORD WaitThread(void *lp)
{
DWORD dwEventMask = 0; // 发生的事件
DWORDTempCount1 = 0;
DWORDTempCount2 = 0;
booltFlag = FALSE;
OVERLAPPEDWatch;
//HANDLEhEvent;
Mscomm *This = (Mscomm*)lp;
memset(&Watch,0,sizeof(Watch));
// 创建一个人工重设
Watch.hEvent = CreateEvent(NULL,FALSE,FALSE,"WatchEvent");
while(This->ThreadFlag)
{
if(WaitCommEvent(This->hComm,&dwEventMask,&Watch));
{
if(dwEventMask == EV_RXCHAR)
{
if(This->InBufferCount != 0)
{
SendMessage(This->wHand ,WM_COMM_RXCHAR,0,0);
dwEventMask = 0;
//while(This->InBufferCount != 0);
}
}
}
}
return 0;
}
//===============线程退出===============
voidExitThread()
{
if(ThreadFlag)
{
ThreadFlag = FALSE;
WaitForSingleObject(hThread,INFINITE);
}
CloseHandle(hThread);
}
public:
//intmPort;//端口号
//设置并返回接收缓冲区的字节数
//__property int InBufferSize = {write=SetInBufferSize};
//以字节的形式设置并返回传输缓冲区的大小
//__property int OutBufferSize = {write=SetOutBufferSize};
Mscomm(HWND hand = NULL);
virtual~Mscomm();
bool OpenComm(int Port); //打开串口
void CloseComm(); //关闭打开的串口
boolCommSetting(char* Setting); //串口设置
boolRedComm(unsigned char* ReadData,//读串口数据
DWORD ReadCount=1);
boolWriteComm(char* Send); //发送数据到串口
__property DWORD InBufferCount = {read=GetInBufferCount,write=SetInBufferCount};
__property DWORD OutBufferCount = {read=GetOutBufferCount,write=SetOutBufferCount};
__property bool RThreshold = {write=SetRThreshold};
//__published:
};
#endif
[解决办法]
楼主这个类是自己写的,为啥起名叫ms呢?
楼主的类只能在有窗口的程序中运行?无法在线程中运行?构造函数要求提供一个窗口句柄。
[解决办法]
楼主搜索cncomm,这个串口类据说是跨平台的,可以在windows,linux,wince上用的