www.pudn.com > SerialPortAPI.rar > SerialPortControl.cpp


#include "StdAfx.h" 
#include "SerialPortControl.h" 
 
HANDLE hCom;//全局变量,串口句柄 
HANDLE hCommThread;//全局变量,串口线程 
SerialPortData comData;//全局变量,串口数据 
 
BOOL OpenSerialPort1() 
{ 
	//打开并设置COM1 
	hCom=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL); 
	if (hCom==(HANDLE)-1) 
	{ 
		AfxMessageBox("打开COM1失败"); 
		return false; 
	} 
	else 
	{ 
		DCB wdcb; 
		GetCommState (hCom,&wdcb); 
		wdcb.BaudRate=9600; 
		SetCommState (hCom,&wdcb); 
		PurgeComm(hCom,PURGE_TXCLEAR); 
	} 
 
	return true; 
} 
 
//以一个线程不同监控串口行接收的数据 
DWORD WINAPI SerialPort1ThreadProcess( HWND hWnd//主窗口句柄 
									  ) 
{ 
	 
	char str[101]; 
	DWORD wCount; //读取的字节数 
	while(1) 
	{ 
		ReadFile(hCom,str, 100, &wCount, NULL); 
		if(wCount > 0)//收到数据 
		{ 
			str[wCount] = '\0'; 
			::PostMessage(hWnd, COM_RECVDATA, (unsigned int)str, wCount);	 
		} 
	} 
	return TRUE; 
}