📄 串口通信dlg.cpp
字号:
// 串口通信Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "串口通信.h"
#include "DataSendDlg.h"
#include "DataReceiveDlg.h"
#include "串口通信Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyDlg dialog
CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMyDlg)
m_Receive = _T("");
m_Send = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMyDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMyDlg)
DDX_Control(pDX, IDC_OPEN_RADIO, m_SetRadio);
DDX_Control(pDX, IDC_MSCOMM, m_Comm);
DDX_Text(pDX, IDC_EDIT_RECEIVE, m_Receive);
DDX_Text(pDX, IDC_EDIT_SEND, m_Send);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
//{{AFX_MSG_MAP(CMyDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
ON_BN_CLICKED(IDC_BUTTON_SAVE, OnButtonSave)
ON_BN_CLICKED(IDC_BUTTON_ABOUT, OnButtonAbout)
ON_BN_CLICKED(IDC_BUTTON_OPENS, OnButtonOpenS)
ON_BN_CLICKED(IDC_BUTTON_OPENR, OnButtonOpenR)
ON_BN_CLICKED(IDC_OPEN_RADIO, OnOpenRadio)
ON_BN_CLICKED(IDC_CLOSE_RADIO, OnCloseRadio)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyDlg message handlers
BOOL CMyDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
// this->InitCOM(1,"9600,n,8,1");
((CComboBox *)this->GetDlgItem(IDC_COMBO_COMNUM))->SetCurSel(0);
((CComboBox *)this->GetDlgItem(IDC_COMBO_RATE))->SetCurSel(2);
((CComboBox *)this->GetDlgItem(IDC_COMBO_CHECK))->SetCurSel(2);
((CComboBox *)this->GetDlgItem(IDC_COMBO_DATA))->SetCurSel(2);
((CComboBox *)this->GetDlgItem(IDC_COMBO_STOP))->SetCurSel(0);
((CComboBox *)this->GetDlgItem(IDC_COMBO_SAVE))->SetCurSel(0);
((CButton *)this->GetDlgItem(IDC_CHECK_SAVE))->SetCheck(1);
this->SetDlgItemText(IDC_EDIT_COMSTATE,"已关闭");
::AfxGetModuleState()->m_dwVersion = 0x0601;
this->m_pRS=new CDaoRecordset(&m_db);
CFileFind fd;
if(!fd.FindFile("temp.mdb"))
{
this->m_db.Create("temp.mdb");
CString sqlcmd="create table Send(时间 VARCHAR(50),数据 VARCHAR(250));";
this->m_db.Execute(sqlcmd);
sqlcmd="create table Receive(时间 VARCHAR(50),数据 VARCHAR(250));";
this->m_db.Execute(sqlcmd);
this->m_db.Close();
}
fd.Close();
this->m_bmp[0].LoadBitmap(IDB_BITMAP_CLOSE);
this->m_bmp[1].LoadBitmap(IDB_BITMAP_OPEN);
//((CStatic *)this->GetDlgItem(IDC_PIC))->SetBitmap(HBITMAP(this->m_bmp[0]));
CheckRadioButton(IDC_OPEN_RADIO,IDC_CLOSE_RADIO,IDC_CLOSE_RADIO);
iSetRadio=FALSE;
return TRUE; // return TRUE unless you set the focus to a control
}
void CMyDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMyDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMyDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CMyDlg::InitCOM(int com_num,CString args)
{
//串口初始化///////////////////////////////////////////////////////////////////////
m_Comm.SetCommPort(com_num); //串口号,一般从1到4
m_Comm.SetInputMode(1); //0-Text 接收数据的类型,0表示文本类型,1表示二进制类型
m_Comm.SetSettings(args);//串口的参数设置,依次为波特率、奇偶校验(n-无校验,e-偶校验,o-奇校验)、数据位数、停止位数
m_Comm.SetRThreshold(1);//设定当接收几个字符时触发OnComm事件,0表示不产生事件,1表示每接收一个字符就产生一个事件
m_Comm.SetInputLen(0); //从接收缓冲区读取的字节数,0表示全部读取
if(!m_Comm.GetPortOpen())//检测是否已经打开过端口
{
m_Comm.SetPortOpen(TRUE); //如没有打开则将端口打开
}
else
AfxMessageBox("Open The Serial Port 1 Failurre!");
m_Comm.GetInput();
///////////////////////////////////////////////////////////////////////////////////
}
void CMyDlg::OnButtonSend()
{
// TODO: Add your control notification handler code here
if(!this->m_Comm.GetPortOpen())
{
AfxMessageBox("COM端口还没有打开!请先设置参数,然后再打开!");
return;
}
this->UpdateData(TRUE);
if(this->m_Send.IsEmpty())
{
AfxMessageBox("请在发送区输入数据!");
return;
}
if(((CButton *)this->GetDlgItem(IDC_CHECK_SAVE))->GetCheck()==1)
this->Save(this->m_Send,'S');
///////////////////////////////////////////////////////////////////字符转十六进制
if(((CButton *)this->GetDlgItem(IDC_CHECK_HEX))->GetCheck()==1)
{
this->m_Send.MakeUpper();
int strlen=this->m_Send.GetLength();
for(int i=0;i<strlen;i++)
{
if(this->m_Send.GetAt(i)>='0'&&this->m_Send.GetAt(i)<='9')
this->m_Send.SetAt(i,this->m_Send.GetAt(i)-'0');
if(this->m_Send.GetAt(i)>='A'&&this->m_Send.GetAt(i)<='F')
this->m_Send.SetAt(i,this->m_Send.GetAt(i)-'A'+10);
}
}
//AfxMessageBox(this->m_Send);
//////////////////////////////////////////////////////////////////
int count=this->m_Send.GetLength();
CByteArray array;
array.RemoveAll();
array.SetSize(count);
for(int i=0;i<count;i++)
array.SetAt(i,this->m_Send[i]);
this->m_Comm.SetOutput(COleVariant(array));
this->m_Send.Empty();
this->UpdateData(FALSE);
}
BEGIN_EVENTSINK_MAP(CMyDlg, CDialog)
//{{AFX_EVENTSINK_MAP(CMyDlg)
ON_EVENT(CMyDlg, IDC_MSCOMM, 1 /* OnComm */, OnComm, VTS_NONE)
//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
void CMyDlg::OnComm()
{
// TODO: Add your control notification handler code here
VARIANT variant;
COleSafeArray safearray;
long i=0;
int len;
char rxdata[1000];
if(this->m_Comm.GetCommEvent()==2)
{
variant=this->m_Comm.GetInput();
safearray=variant;
len=safearray.GetOneDimSize();
for(i=0;i<len;i++)
safearray.GetElement(&i,&rxdata[i]);
rxdata[i]='\0';
///////////////////////////////////////////////////////////////十六进制转字符
// AfxMessageBox(rxdata);
if(((CButton *)this->GetDlgItem(IDC_CHECK_HEX))->GetCheck()==1)
{
for(int j=0;j<i;j++)
{
if(rxdata[j]>=0&&rxdata[j]<=9)
rxdata[j]+='0';
if(rxdata[j]>=10&&rxdata[j]<=15)
rxdata[j]=rxdata[j]+'A'-10;
}
}
///////////////////////////////////////////////////////////////
this->m_Receive+=rxdata;
}
this->UpdateData(FALSE);
}
void CMyDlg::OnOK()
{
// TODO: Add extra validation here
if(this->m_Receive.IsEmpty())
return;
if(AfxMessageBox("数据还没有保存,是否保存?",1)==1)
this->Save(this->m_Receive,'R');
this->m_Receive.Empty();
this->UpdateData(false);
//CDialog::OnOK();
}
void CMyDlg::Save(CString strdata,char flag)
{
// TODO: Add your control notification handler code here
CString temp,filename=_T("Temp.txt");
if(flag=='R')filename=_T("Receive.txt");
if(flag=='S')filename=_T("Send.txt");
this->GetDlgItemText(IDC_COMBO_SAVE,temp);
if(temp.Compare("文本")==0)
{
temp.Empty();
CFile fp;
if(!fp.Open(filename,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate,NULL))
{
AfxMessageBox("不能打开保存文件!");
fp.Close();
return;
}
fp.SeekToEnd();
CTime t=CTime::GetCurrentTime();
temp.Format("时间:%d年%d月%d日%d时%d分%d秒",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond());
fp.Write(temp,temp.GetLength());
temp.Empty();
temp=" 数据内容:";
fp.Write(temp,temp.GetLength());
temp.Empty();
fp.Write(strdata,strdata.GetLength());
temp.Format(" 数据长度:%d字节。",strdata.GetLength());
fp.Write(temp,temp.GetLength());
temp.Empty();
fp.Write("\r\n",2);
}
else
{
CTime tt=CTime::GetCurrentTime();
CString strtemp;
strtemp.Format("%d年%d月%d日%d时%d分%d秒",tt.GetYear(),tt.GetMonth(),tt.GetDay(),tt.GetHour(),tt.GetMinute(),tt.GetSecond());
try
{
this->m_db.Open("temp.mdb");
if(flag=='S')
{
this->m_pRS->Open(AFX_DAO_USE_DEFAULT_TYPE,"select * from Send",NULL);
this->m_pRS->AddNew();
this->m_pRS->SetFieldValue("时间",strtemp.GetBuffer(0));
this->m_pRS->SetFieldValue("数据",this->m_Send.GetBuffer(0));
this->m_pRS->Update();
}
if(flag=='R')
{
this->m_pRS->Open(AFX_DAO_USE_DEFAULT_TYPE,"select * from Receive",NULL);
this->m_pRS->AddNew();
this->m_pRS->SetFieldValue("时间",strtemp.GetBuffer(0));
this->m_pRS->SetFieldValue("数据",this->m_Receive.GetBuffer(0));
this->m_pRS->Update();
}
this->m_pRS->Close();
}
catch(CDaoException *e)
{
// DispDaoException(e);
AfxMessageBox("不能打开数据库!");
}
this->m_db.Close();
}
}
void CMyDlg::OnButtonSave()
{
// TODO: Add your control notification handler code here
if(this->m_Receive.IsEmpty())
return;
this->Save(this->m_Receive,'R');
this->m_Receive.Empty();
this->UpdateData(false);
}
void CMyDlg::OnButtonAbout()
{
// TODO: Add your control notification handler code here
CAboutDlg dlg;
dlg.DoModal();
}
BOOL CMyDlg::DestroyWindow()
{
// TODO: Add your specialized code here and/or call the base class
delete this->m_pRS;
return CDialog::DestroyWindow();
}
void CMyDlg::OnButtonOpenS()
{
// TODO: Add your control notification handler code here
CString temp;
this->GetDlgItemText(IDC_COMBO_SAVE,temp);
if(temp.Compare("文本")==0)
{
::ShellExecute(NULL, "open","Send.txt", NULL, NULL, SW_SHOWNORMAL);
}
else
{
CDataSendDlg dlgs;
dlgs.DoModal();
}
}
void CMyDlg::OnButtonOpenR()
{
// TODO: Add your control notification handler code here
CString temp;
this->GetDlgItemText(IDC_COMBO_SAVE,temp);
if(temp.Compare("文本")==0)
{
::ShellExecute(NULL, "open","Receive.txt", NULL, NULL, SW_SHOWNORMAL);
}
else
{
CDataReceiveDlg dlgr;
dlgr.DoModal();
}
}
void CMyDlg::OnOpenRadio()
{
// TODO: Add your control notification handler code here
// int iSetRadio;
// iSetRadio=GetCheckedRadioButton(IDC_OPEN_RADIO,IDC_CLOSE_RADIO);
// if(!(iSetRadio==IDC_OPEN_RADIO))
if(iSetRadio==FALSE)
{
CString args,temp;
int com_num=1;
this->GetDlgItemText(IDC_COMBO_COMNUM,temp);
if(temp.Compare("COM2")==0)
com_num=2;
temp.Empty();
this->GetDlgItemText(IDC_COMBO_RATE,temp);
if(temp.Compare("1200")==0||temp.Compare("2400")==0||temp.Compare("9600")==0)
args=temp;
else
args="9600";
args+=",";
temp.Empty();
this->GetDlgItemText(IDC_COMBO_CHECK,temp);
if(temp.Compare("无校验")==0)
args+="n,";
if(temp.Compare("偶校验")==0)
args+="e,";
if(temp.Compare("奇校验")==0)
args+="o,";
temp.Empty();
this->GetDlgItemText(IDC_COMBO_DATA,temp);
if(temp.Compare("6")==0||temp.Compare("7")==0||temp.Compare("8")==0)
args+=temp+",";
else
args+="8,";
temp.Empty();
this->GetDlgItemText(IDC_COMBO_STOP,temp);
if(temp.Compare("1")==0||temp.Compare("2")==0)
args+=temp;
else
args+="1";
this->InitCOM(com_num,args);
this->SetDlgItemText(IDC_EDIT_COMSTATE,"已打开");
iSetRadio=TRUE;
}
}
void CMyDlg::OnCloseRadio()
{
// TODO: Add your control notification handler code here
// int iSetRadio;
// iSetRadio=GetCheckedRadioButton(IDC_OPEN_RADIO,IDC_CLOSE_RADIO);
// if(!(iSetRadio==IDC_CLOSE_RADIO))
if(iSetRadio==TRUE)
{
this->m_Comm.SetPortOpen(false);
this->SetDlgItemText(IDC_EDIT_COMSTATE,"已关闭");
iSetRadio=FALSE;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -