?? 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 = 2; //默認為com1
m_strBits = "1200";
m_strDataBit = "8";
m_strParity = "n";
m_strStopBit = "1";
m_strSeting = "1200, n, 8, 1"; //默認設置
m_strStatus = "Status: COM3 Open: TURE, 1200,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 + -