资源描述:
《C语言串口通信助手代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、该程序全部由C写成没有C++更没用MFC完全是自娱自乐给需要的人一个参考#include"stdafx.h"#include#include"resource.h"#include"MainDlg.h"#include#include#includeHANDLEhComm;//用于获取串口打开函数的返回值(句柄或错误值)OVERLAPPEDm_ov;COMSTATcomstat;DWORDm_dwCommEvents;T
2、CHARcRecs[200],cSends[100];//接收字符串发送字符串charj=0,*cCom;//接收用统计数据大小变量端口选择BOOLWINAPIMain_Proc(HWNDhWnd,UINTuMsg,WPARAMwParam,LPARAMlParam){switch(uMsg){HANDLE_MSG(hWnd,WM_INITDIALOG,Main_OnInitDialog);HANDLE_MSG(hWnd,WM_COMMAND,Main_OnCommand);HANDLE_MSG(hWn
3、d,WM_CLOSE,Main_OnClose);}returnFALSE;}/*系统初始化函数*/BOOLMain_OnInitDialog(HWNDhwnd,HWNDhwndFocus,LPARAMlParam){HWNDhwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);ComboBox_InsertString(hwndCombo1,-1,TEXT("COM1"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM2"));Co
4、mboBox_InsertString(hwndCombo1,-1,TEXT("COM3"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM4"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM5"));ComboBox_SetCurSel(hwndCombo1,0);voidCALLBACKTimerProc(HWNDhwnd,UINTmessage,UINTiTimerID,DWORDdwTime);SetT
5、imer(hwnd,1,1000,TimerProc);returnTRUE;}/*监视串口错误时使用的函数*/boolProcessErrorMessage(char*ErrorText){char*Temp=newchar[200];LPVOIDlpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
6、FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL,SUBL
7、ANG_DEFAULT),//Defaultlanguage(LPTSTR)&lpMsgBuf,0,NULL);sprintf(Temp,"WARNING:%sFailedwiththefollowingerror:%sPort:%d",(char*)ErrorText,lpMsgBuf,"com2");MessageBox(NULL,Temp,"ApplicationError",MB_ICONSTOP);LocalFree(lpMsgBuf);delete[]Temp;returntru
8、e;}boolopenport(char*portname)//打开串口{hComm=CreateFile(portname,//串口号“com1”“com2”调用方法:boolopen;open=openport("com2");GENERIC_READ
9、GENERIC_WRITE,//允许读写0,//通讯设备必须以独占方式打开0,//无安全属性OPEN_EXISTING,//通讯设备已存在FILE_FLAG_OVERLAPPED,//异步I/O0);//通讯设备不能用模板打开if(hComm==IN
10、VALID_HANDLE_VALUE)//如果被占用或是没有打开时返回的是这个错误代码{CloseHandle(hComm);returnFALSE;}elsereturntrue;}boolsetupdcb(intrate_arg)//设置port的属性{DCBdcb;intrate=rate_arg;memset(&dcb,0,sizeof(dcb));if(!GetCommState(hComm,&dcb))//获取当前DCB配置re