WinApi实现串口通信

GetDlgItem(IDC_CLOSEPORT)->EnableWindow(false);  //使关闭按钮失效

建立对话框,并给发送接收关联变量。

头文件中加入如下代码:

 HANDLE hCom;   //定义串口句柄
 OVERLAPPED Wol;   //写操作OVERLAPPED结构变量
 OVERLAPPED Rol;   //写操作OVERLAPPED结构变量
 BYTE myWByte[300];  //存放欲写的数据
 BYTE myRByte[300];  //存放欲读的数据
 long dataWLen;   //发送数据的长度
 CDialog mySetupDlg;  //声明设置对话框实例
 LPCTSTR myCom;   //串口声明
 BYTE myParity;   //串口名称
 DWORD myfParity;  //奇偶校验位
 DWORD myBaudRate;  //是否使用奇偶校验位
 bool blnOpened;   //串口已经打开标志

 

分别给各个按钮添加消息映射,并添加代码:

//串口操作添加代码

void CWin32ApiSeriaDlg::OnSetport()      //设置串口消息处理
{
 // TODO: Add your control notification handler code here
 myCom="COM4";
 myBaudRate=CBR_9600;
 myfParity=false;
 myParity=NOPARITY;

}

void CWin32ApiSeriaDlg::OnOpenport()      //打开串口
{
 // TODO: Add your control notification handler code here
  // TODO: Add your control notification handler code here
 CString strDis;
 hCom=CreateFile(myCom,
  GENERIC_READ | GENERIC_WRITE,
  0,
  NULL,OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  NULL);
 if(hCom!=INVALID_HANDLE_VALUE)
 {
  SetupComm(hCom,1024,512);
  DCB myDCB;
  GetCommState(hCom,&myDCB);
  myDCB.BaudRate=myBaudRate;
  myDCB.fParity=myfParity;
  myDCB.fBinary=TRUE;
  myDCB.ByteSize=8;
  myDCB.Parity=myParity;
  myDCB.StopBits=ONESTOPBIT;
  SetCommState(hCom,&myDCB);
  AfxMessageBox("串口打开成功!");
  blnOpened=true;
 }
 else
 {
  AfxMessageBox("串口打开失败!");
  blnOpened=false;
 }
 GetDlgItem(IDC_OPENPORT)->EnableWindow(!blnOpened);  //使打开按钮失效
 GetDlgItem(IDC_CLOSEPORT)->EnableWindow(blnOpened);  //使能关闭按钮
}

void CWin32ApiSeriaDlg::OnCloseport()      //关闭串口
{
 // TODO: Add your control notification handler code here
 if((blnOpened) && (hCom!=NULL))  //若串口打开标志为真,且串口句柄不为空则执行关闭串口的操作
 {
  CloseHandle(hCom);
  AfxMessageBox("串口已经关闭!");
  blnOpened=false;
 }
 else
 {
  AfxMessageBox("串口未打开!");
 }
 
 GetDlgItem(IDC_OPENPORT)->EnableWindow(!blnOpened);   //使能打开按钮
 GetDlgItem(IDC_CLOSEPORT)->EnableWindow(blnOpened);  //使关闭按钮失效
}

void CWin32ApiSeriaDlg::OnSend()      //发送按键处理

 // TODO: Add your control notification handler code here
 myWByte[0]='a';
 dataWLen=1;
 Wol.Internal=0;
 Wol.InternalHigh=0;
 Wol.Offset=0;
 Wol.OffsetHigh=0;
 Wol.hEvent=CreateEvent(NULL,
  TRUE,
  FALSE,
  NULL);
 WriteFile(hCom,&myWByte,dataWLen,NULL,&Wol); //发送字符
 Beep(1000,10);
 
}

添加接收字符的消息生命和消息映射

头文件中 afx_msg LRESULT OnComm(WPARAM wParam, LPARAM lParam);

C++文件中BEGIN_MESSAGE_MAP和END_MESSAGE_MAP()之间添加

 ON_MESSAGE(WM_COMMNOTIFY, OnComm)

然后再在下面添加函数实体

LRESULT CWin32ApiSeriaDlg::OnComm(WPARAM wParam, LPARAM lParam)
{
 BYTE myByte[50];
 DWORD dwLength;
 DWORD length=0;

 COMSTAT ComStat;
 DWORD dwErrorFlags;

 Rol.Internal=0;
 Rol.InternalHigh=0;
 Rol.Offset=0;
 Rol.OffsetHigh=0;
 Rol.hEvent=CreateEvent(NULL,
  TRUE,
  FALSE,
  NULL);

 ClearCommError(hCom,&dwErrorFlags,&ComStat);
 length=min(100, ComStat.cbInQue);

 ReadFile(hCom,&myByte,ComStat.cbInQue,NULL,&Rol);

 m_strRxMsg+=myByte[0];
 UpdateData(false);

 return 0;
}

你可能感兴趣的:(WinApi实现串口通信)