📄 rs232dlg.cpp
字号:
// RS232Dlg.cpp : implementation file
//
#include "stdafx.h"
#include "RS232.h"
#include "RS232Dlg.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()
/////////////////////////////////////////////////////////////////////////////
// CRS232Dlg dialog
CRS232Dlg::CRS232Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CRS232Dlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CRS232Dlg)
m_RXD = _T("");
m_TXD = _T("");
m_strBits = _T("");
m_strDataBit = _T("");
m_strParity = _T("");
m_strStopBit = _T("");
m_strStatus = _T("");
m_nCom = -1;
m_strPath = _T("");
m_time = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
//变量初始化
m_nCom = 0; //默认为com1
m_strBits = "9600";
m_strDataBit = "8";
m_strParity = "n";
m_strStopBit = "1";
m_strSeting = "9600, n, 8, 1"; //默认设置
m_strStatus = "Status: COM1 Open: TURE, 9600,n,8,1";
m_bPortOpen = 0; //默认端口没有打开
m_time = "1000"; //默认发送时间间隔为1000ms
m_bAutoSend = 0; //默认为不自动发送
}
void CRS232Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRS232Dlg)
DDX_Control(pDX, IDC_STATIC_ICON, m_ctrlIcon);
DDX_Control(pDX, IDC_CHECK_HEXSEND, m_ctrlHexSend);
DDX_Control(pDX, IDC_CHECK_HEX, m_ctrlHexdisp);
DDX_Text(pDX, IDC_EDIT_RXD, m_RXD);
DDX_Text(pDX, IDC_EDIT_TXD, m_TXD);
DDX_Control(pDX, IDC_MSCOMM1, m_Comm);
DDX_CBString(pDX, IDC_COMBO_BITS, m_strBits);
DDX_CBString(pDX, IDC_COMBO_DATA, m_strDataBit);
DDX_CBString(pDX, IDC_COMBO_PARITY, m_strParity);
DDX_CBString(pDX, IDC_COMBO_STOP, m_strStopBit);
DDX_Text(pDX, IDC_EDIT_STATUS, m_strStatus);
DDX_CBIndex(pDX, IDC_COMBO_COM, m_nCom);
DDX_Text(pDX, IDC_EDIT_PATH, m_strPath);
DDX_Text(pDX, IDC_EDIT_TIME, m_time);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRS232Dlg, CDialog)
//{{AFX_MSG_MAP(CRS232Dlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
ON_BN_CLICKED(IDC_BUTTON_CLOSE, OnButtonClose)
ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear)
ON_BN_CLICKED(IDC_BUTTON_CLEARS, OnButtonClears)
ON_CBN_SELCHANGE(IDC_COMBO_COM, OnSelchangeComboCom)
ON_CBN_SELCHANGE(IDC_COMBO_BITS, OnSelchangeComboBits)
ON_CBN_SELCHANGE(IDC_COMBO_PARITY, OnSelchangeComboParity)
ON_CBN_SELCHANGE(IDC_COMBO_DATA, OnSelchangeComboData)
ON_CBN_SELCHANGE(IDC_COMBO_STOP, OnSelchangeComboStop)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_BUTTON_AUTOSEND, OnButtonAutosend)
ON_BN_CLICKED(IDC_BUTTON_FILE, OnButtonFile)
ON_BN_CLICKED(IDC_BUTTON_SENDFILE, OnButtonSendfile)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRS232Dlg message handlers
BOOL CRS232Dlg::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
((CComboBox*)GetDlgItem(IDC_COMBO_COM))->SetCurSel(m_nCom); //设置默认打开串口
UpdateData(FALSE);
this->OpenCOM(); //打开串口
return TRUE; // return TRUE unless you set the focus to a control
}
void CRS232Dlg::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 CRS232Dlg::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 CRS232Dlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CRS232Dlg::OnButtonSend()
{ //发送字符
// TODO: Add your control notification handler code here
UpdateData(TRUE);
SendString(m_TXD); //调用发送字符子函数
}
BEGIN_EVENTSINK_MAP(CRS232Dlg, CDialog)
//{{AFX_EVENTSINK_MAP(CRS232Dlg)
ON_EVENT(CRS232Dlg, IDC_MSCOMM1, 1 /* OnComm */, OnComm, VTS_NONE)
//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
void CRS232Dlg::OnComm()
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
CString strtemp;
if(m_Comm.GetCommEvent() == 2) //事件值为2表示接收缓冲区内有字符
{ ////////以下你可以根据自己的通信协议加入处理代码
variant_inp = m_Comm.GetInput(); //读缓冲区
safearray_inp = variant_inp; //VARIANT型变量转换为ColeSafeArray型变量
len = safearray_inp.GetOneDimSize(); //得到有效数据长度
for(k = 0; k < len; k++)
safearray_inp.GetElement(&k, rxdata+k);//转换为BYTE型数组
for(k = 0;k<len;k++) //将数组转换为Cstring型变量
{
BYTE bt = *(char*)(rxdata+k); //字符型
if (m_ctrlHexdisp.GetCheck())
strtemp.Format("%02X ", bt); //以十六进制显示
else
strtemp.Format("%c",bt); //将字符送入临时变量strtemp存放
m_RXD += strtemp; //加入接收编辑框对应字符串
}
}
UpdateData(FALSE); //更新编辑框内容
}
void CRS232Dlg::OnButtonClose()
{
// TODO: Add your control notification handler code here
if (m_Comm.GetPortOpen())
{
m_Comm.SetPortOpen(FALSE);
m_bPortOpen = 0;
this->SetDlgItemText(IDC_BUTTON_CLOSE, "打开串口");
}
else
{
m_Comm.SetPortOpen(TRUE);
m_bPortOpen = 1;
this->SetDlgItemText(IDC_BUTTON_CLOSE, "关闭串口");
}
ShowStatus();
}
void CRS232Dlg::OpenCOM()
{ //打开串口
m_Comm.SetCommPort(m_nCom+1); //设置打开com口
m_bPortOpen = 1; //置打开状态为1
m_Comm.SetSettings(m_strSeting); //设置端口
m_Comm.SetInputMode(1); //以二进制方式捡取
m_Comm.SetRThreshold(1); //当缓冲区中有一个以上字符时触发事件
m_Comm.SetDTREnable(TRUE);
m_Comm.SetRTSEnable(TRUE);
if (!m_Comm.GetPortOpen()) //如果端口没有打开
m_Comm.SetPortOpen(TRUE); //则打开选定端口
m_Comm.SetInputLen(0); //读取控件中缓冲区中全部内容
m_Comm.GetInput(); //预读缓冲区,清除残留数据
ShowStatus();
}
void CRS232Dlg::OnButtonClear()
{
// TODO: Add your control notification handler code here
m_RXD = "";
SetDlgItemText(IDC_EDIT_RXD,"");
}
void CRS232Dlg::OnButtonClears()
{
// TODO: Add your control notification handler code here
m_TXD = "";
SetDlgItemText(IDC_EDIT_TXD,"");
}
void CRS232Dlg::OnSelchangeComboCom()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_Comm.GetPortOpen())
m_Comm.SetPortOpen(FALSE); //如果当前端口打开了则关上
OpenCOM(); //然后打开新的选择的端口
}
void CRS232Dlg::OnSelchangeComboBits()
{
// TODO: Add your control notification handler code here
this->ChangSetting();
}
void CRS232Dlg::OnSelchangeComboParity()
{
// TODO: Add your control notification handler code here
this->ChangSetting();
}
CString CRS232Dlg::parity(CString str)
{ //把奇偶校验位转换为规范的表示
if (str == "None无")
return "n";
else if (str == "ODD奇")
return "o";
else if (str == "EVEN偶")
return "e";
}
void CRS232Dlg::ShowStatus()
{//状态栏显示状态
CString com[4] = {"COM1", "COM2", "COM3", "COM4"};
CString portopen[2] = {"Closed", "Opend"};
m_strStatus = "Status: " + com[m_nCom] +": " + portopen[m_bPortOpen] + ", Setting: " + m_strSeting;
if (m_bPortOpen == FALSE)
m_ctrlIcon.SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance,
MAKEINTRESOURCE(IDI_ICON_CLOSE),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CXICON),
0)); //显示关闭icon
else
m_ctrlIcon.SetIcon((HICON)LoadImage(AfxGetApp()->m_hInstance,
MAKEINTRESOURCE(IDI_ICON_OPEN),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CXICON),
0)); //显示打开icon
UpdateData(FALSE);
}
void CRS232Dlg::ChangSetting()
{
UpdateData(TRUE); //如果设置改变了则更新数据
m_strSeting = m_strBits+","+parity(m_strParity) +
"," + m_strDataBit + "," + m_strStopBit; //重新设置打开设置
if (m_Comm.GetPortOpen())
m_Comm.SetPortOpen(FALSE); //如果当前端口打开了则关上
OpenCOM(); //重新打开
}
void CRS232Dlg::OnSelchangeComboData()
{
// TODO: Add your control notification handler code here
this->ChangSetting();
}
void CRS232Dlg::OnSelchangeComboStop()
{
// TODO: Add your control notification handler code here
this->ChangSetting();
}
int CRS232Dlg::String2Hex(CString str, CByteArray &senddata)
{ //将字符串转换为16进制,俩个字符间插入了一个空格
int hexdata, lowhexdata;
int hexdatalen = 0;
int len = str.GetLength();
senddata.SetSize(len/2);
for (int i = 0; i < len; )
{
char lstr, hstr = str[i];
if (hstr == ' ') //如果遇到空格则跳过
{
i++;
continue;
}
i++;
if (i >= len)
break;
lstr = str[i];
if ((hexdata = ConvertHexChar(hstr)) == -1)
{
AfxMessageBox("输入字符超出16进制范围,无法按16进制正常发送",MB_ICONERROR); //将高字符转换为16进制字符
return -1;
}
if ((lowhexdata = ConvertHexChar(lstr)) == -1) //再将低字符转换为16进制字符
{
AfxMessageBox("输入字符超出16进制范围,无法按16进制正常发送",MB_ICONERROR); //将高字符转换为16进制字符
return -1;
}
if ((hexdata ==16) || (lowhexdata == 16))
break; //如果这俩个字符中任意一个大于16则跳出
else
hexdata = hexdata*16 + lowhexdata; //否则把俩个字符叠加
i++;
senddata[hexdatalen] = (char)hexdata; //保存到要发送的缓冲区中
hexdatalen++;
}
senddata.SetSize(hexdatalen);
return hexdatalen;
}
char CRS232Dlg::ConvertHexChar(char ch)
{ //将一个字符转换为相应的十六进制
if ((ch >= '0') && (ch <= '9'))
return ch - 0x30;
else if ((ch >= 'A') && (ch <= 'F'))
return ch - 'A' + 10;
else if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
else
return (-1);
}
void CRS232Dlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
OnButtonSend();
CDialog::OnTimer(nIDEvent);
}
void CRS232Dlg::OnButtonAutosend()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_bAutoSend = !m_bAutoSend;
if (m_bAutoSend)
{
SetTimer(1, atoi(m_time.GetBuffer(m_time.GetLength())), NULL); //设置定时
SetDlgItemText(IDC_BUTTON_AUTOSEND, "停止");
}
else
{
KillTimer(1);
SetDlgItemText(IDC_BUTTON_AUTOSEND, "自动发送");
}
}
void CRS232Dlg::OnButtonFile()
{
// TODO: Add your control notification handler code here
CFile file;
CFileDialog FileDlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"文本文件(*.txt)|*.txt||");
if (FileDlg.DoModal() == IDOK) //打开文件对话框
m_strPath = FileDlg.GetPathName(); //得到文件路经
UpdateData(FALSE);
file.Open(m_strPath, CFile::modeRead | CFile::typeBinary); //打开这个文件
file.Read(m_strFile.GetBuffer(file.GetLength()), file.GetLength()); //读文件
file.Close();
}
void CRS232Dlg::OnButtonSendfile()
{
// TODO: Add your control notification handler code here
SendString(m_strFile);
}
void CRS232Dlg::SendString(CString str)
{
if (m_ctrlHexSend.GetCheck())
{
CByteArray hexdata;
int len = String2Hex(str, hexdata); //len为发送多少个十六进制字符
if (len == -1)
return;
m_Comm.SetOutput(COleVariant(hexdata)); //发送十六进制数据
}
else
m_Comm.SetOutput(COleVariant(str));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -