⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serialcommdlg.cpp

📁 实现串口通讯功能
💻 CPP
字号:
// SerialCommDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SerialComm.h"
#include "SerialCommDlg.h"
#include <io.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()

/////////////////////////////////////////////////////////////////////////////
// CSerialCommDlg dialog

CSerialCommDlg::CSerialCommDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSerialCommDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSerialCommDlg)
	m_strRXData = _T("");
	m_strTXData = _T("");
	m_strCurPath = _T("");
	m_strSendFilePathName = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON4);
	m_bAutoSend=FALSE;
	m_strCurPath="C:\\COMDATA";
}

void CSerialCommDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSerialCommDlg)
	DDX_Control(pDX, IDC_BUTTON_CLOSE, m_ctrlClose);
	DDX_Control(pDX, IDC_EDIT_TXDATA, m_ctrlTXData);
	DDX_Control(pDX, IDC_EDIT_SAVEPATH, m_ctrlSavePath);
	DDX_Control(pDX, IDC_BUTTON_CLOSEPORT, m_ctrlClosePort);
	DDX_Control(pDX, IDC_BUTTON_OPENPORT, m_ctrlOpenPort);
	DDX_Control(pDX, IDC_BUTTON_CLEAR2, m_ctrlClean);
	DDX_Control(pDX, IDC_CHECK_HEXDISPLAY, m_ctrlHexDisplay);
	DDX_Control(pDX, IDC_CHECK_AUTOSEND, m_ctrlAutoSend);
	DDX_Control(pDX, IDC_CHECK_HEXSEND, m_ctrlHexSend);
	DDX_Control(pDX, IDC_MSCOMM1, m_ctrlComm);
	DDX_Text(pDX, IDC_EDIT_RXDATA, m_strRXData);
	DDX_Text(pDX, IDC_EDIT_TXDATA, m_strTXData);
	DDX_Text(pDX, IDC_EDIT_SAVEPATH, m_strCurPath);
	DDX_Text(pDX, IDC_EDIT_SENDFILE, m_strSendFilePathName);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSerialCommDlg, CDialog)
	//{{AFX_MSG_MAP(CSerialCommDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_MANUALSEND, OnButtonManualsend)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR2, OnButtonClear2)
	ON_BN_CLICKED(IDC_CHECK_AUTOSEND, OnCheckAutosend)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_OPENPORT, OnButtonOpenport)
	ON_BN_CLICKED(IDC_BUTTON_CLOSEPORT, OnButtonCloseport)
	ON_BN_CLICKED(IDC_BUTTON_SAVADATA, OnButtonSavadata)
	ON_BN_CLICKED(IDC_BUTTON_DIRBROWSER, OnButtonDirbrowser)
	ON_BN_CLICKED(IDC_BUTTON_FILEBROWSER, OnButtonFilebrowser)
	ON_BN_CLICKED(IDC_BUTTON_CLOSE, OnButtonClose)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSerialCommDlg message handlers

BOOL CSerialCommDlg::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

	m_ctrlComm.SetCommPort(1);
	m_ctrlComm.SetCommPort(1);
	if(!m_ctrlComm.GetPortOpen())
		m_ctrlComm.SetPortOpen(TRUE);
	else
		AfxMessageBox("cannot open port");
	m_ctrlComm.SetSettings("9600,n,8,1");
	m_ctrlComm.SetInputMode(1);
	m_ctrlComm.SetRThreshold(1);
	m_ctrlComm.SetInputLen(0);
	m_ctrlComm.GetInput();

	m_ctrlOpenPort.EnableWindow(FALSE);
	m_ctrlOpenPort.ShowWindow(FALSE);

	m_ctrlClosePort.EnableWindow(TRUE);
	m_ctrlClosePort.ShowWindow(TRUE);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSerialCommDlg::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 CSerialCommDlg::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 CSerialCommDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

BEGIN_EVENTSINK_MAP(CSerialCommDlg, CDialog)
    //{{AFX_EVENTSINK_MAP(CSerialCommDlg)
	ON_EVENT(CSerialCommDlg, IDC_MSCOMM1, 1 /* OnComm */, OnComm, VTS_NONE)
	//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()

void CSerialCommDlg::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_ctrlComm.GetCommEvent()==2)     //事件值为2表示接收缓冲区内有字符
	{
		variant_inp=m_ctrlComm.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_ctrlHexDisplay.GetCheck())
				strtemp.Format("%02X ",bt); //将字符以十六进制方式送入临时变量strtemp存放,注意这里加入一个空隔
			else 
				strtemp.Format("%c",bt); //将字符送入临时变量strtemp存放
			         
			m_strRXData+=strtemp;    //加入接收编辑框对应字符串    
		}
	}

// 	CEdit* pedit=(CEdit*)GetDlgItem(IDC_EDIT_TXDATA);
// 	CString str;
// 	pedit->GetWindowText(str);   //将发送框的内容保存至m_strTXData中
// 	m_strTXData=str;
	CEdit* pEdit=(CEdit*)GetDlgItem(IDC_EDIT_TXDATA);
	pEdit->GetWindowText(m_strTXData);

	UpdateData(FALSE);           //更新编辑框内容
}

void CSerialCommDlg::OnButtonManualsend() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE); //读取编辑框内容
	if(m_ctrlHexSend.GetCheck())
	{
		CByteArray hexdata;
		int len=String2Hex(m_strTXData,hexdata);  //此处返回的len可以用于计算发送了多少个十六进制数
		m_ctrlComm.SetOutput(COleVariant(hexdata));  //发送十六进制数据
	}
	else 
		m_ctrlComm.SetOutput(COleVariant(m_strTXData));//发送ASCII字符数据
	
}

int CSerialCommDlg::String2Hex(CString str, CByteArray &senddata)
{
	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];
		hexdata=ConvertHexChar(hstr);
		lowhexdata=ConvertHexChar(lstr);
		if((hexdata==16)||(lowhexdata==16))
			break;
		else 
			hexdata=hexdata*16+lowhexdata;
		i++;
		senddata[hexdatalen]=(char)hexdata;
		hexdatalen++;
	}
	senddata.SetSize(hexdatalen);
	return hexdatalen;
	
	
}

char CSerialCommDlg::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 CSerialCommDlg::OnButtonClear() 
{
	// TODO: Add your control notification handler code here
/*    m_strTXData+="";*/
/*	SetDlgItemText(IDC_EDIT_RXDATA,"");*/
	m_strRXData.Empty();
	CEdit* pEdit=(CEdit*)GetDlgItem(IDC_EDIT_TXDATA);
	pEdit->GetWindowText(m_strTXData);//保存发送框的数据
	UpdateData(FALSE);
	
}

void CSerialCommDlg::OnButtonClear2() 
{
	// TODO: Add your control notification handler code here
/*	SetDlgItemText(IDC_EDIT_TXDATA,"");*/
// 	m_edit1.SetWindowText(""); 
// 	m_ctrlClean.SetWindowText("");
	m_strTXData.Empty();
	UpdateData(FALSE);
	
}

void CSerialCommDlg::OnCheckAutosend() 
{
	// TODO: Add your control notification handler code here
	m_bAutoSend=!m_bAutoSend;
	if(m_bAutoSend)
	{
		SetTimer(1,1000,NULL);
	}
	else
	{
		KillTimer(1);
	}
}

void CSerialCommDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	switch(nIDEvent)
	{
	case 1:
	   OnButtonManualsend();
	   break;
	case 2:
		m_ctrlSavePath.SetWindowText(m_strCurPath);
		KillTimer(2);
		break;
	default:
		break;
	}

	CDialog::OnTimer(nIDEvent);
}

void CSerialCommDlg::OnButtonOpenport() 
{
	// TODO: Add your control notification handler code here

	m_ctrlComm.SetCommPort(1);
	if(!m_ctrlComm.GetPortOpen())
		m_ctrlComm.SetPortOpen(TRUE);
	else
		AfxMessageBox("cannot open port");

	m_ctrlOpenPort.EnableWindow(FALSE);
	m_ctrlClosePort.EnableWindow(TRUE);

	m_ctrlOpenPort.ShowWindow(FALSE);
	m_ctrlClosePort.ShowWindow(TRUE);

}

void CSerialCommDlg::OnButtonCloseport() 
{
	// TODO: Add your control notification handler code here

	if(m_ctrlAutoSend.GetCheck())
	{
		AfxMessageBox("连续发送时不能关闭串口");

		m_ctrlClosePort.EnableWindow(TRUE);
		m_ctrlOpenPort.EnableWindow(FALSE);
		m_ctrlOpenPort.ShowWindow(FALSE);
		m_ctrlClosePort.ShowWindow(TRUE);

	}
	else
	{
		if(m_ctrlComm.GetPortOpen())
			m_ctrlComm.SetPortOpen(FALSE);

		m_ctrlClosePort.EnableWindow(FALSE);
		m_ctrlOpenPort.EnableWindow(TRUE);
		
		m_ctrlOpenPort.ShowWindow(TRUE);
		m_ctrlClosePort.ShowWindow(FALSE);
	}



}

void CSerialCommDlg::OnButtonSavadata() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
	int nLength;
	nLength=m_strCurPath.GetLength();
	
	for(int nCount=0;nCount<nLength;nCount++)
	{
		if(m_strCurPath.GetAt(nCount)=='\\')
			CreateDirectory(m_strCurPath.Left(nCount+1),NULL);
	}
	CreateDirectory(m_strCurPath,NULL);
	
	CFile m_rFile;
	LPCSTR lpszPath=m_strCurPath;//"C:\\comdata"
	SetCurrentDirectory(lpszPath);
	
	/*文件名为Data**.txt,以下代码自动检测文件名是否存在,如果
	存在,则后面序号自动递增
	*/
	char buf[20];
	for(int j=0;j<100;j++)
	{
		sprintf(buf,"Data%02d.txt",j);
		if(access(buf,0)==-1)
			break;
	}
	if(!m_rFile.Open(buf,CFile::modeCreate|CFile::modeWrite))
	{
		AfxMessageBox("创建记录文件失败!");
		return;
	}
	if((access(buf,0))==-1)
	{
		AfxMessageBox("failed");
		return;
	}
	//在文件开始处写上保存日期
	CTime t=CTime::GetCurrentTime();
	CString str=t.Format("%Y年%m月%d日%H时%m分%S秒\r\n");
	m_rFile.Write((LPCTSTR)str,str.GetLength());
	//保存显示数据
	m_rFile.Write((LPCTSTR)m_strRXData,m_strRXData.GetLength());
	m_rFile.Flush();
	m_rFile.Close();//关闭文件
	
	str="";
	for(int i=0;i<5;i++)
		str+=buf[i];
	str+=".txt 保存";
	m_ctrlSavePath.SetWindowText(str);
	SetTimer(2,5000,NULL);
}

void CSerialCommDlg::OnButtonDirbrowser() 
{
	// TODO: Add your control notification handler code here
	static char displayname[MAX_PATH];
	static char path[MAX_PATH];
	LPITEMIDLIST pidlBrowse;
	BROWSEINFO bi;
	bi.hwndOwner=this->m_hWnd;
	bi.pidlRoot=NULL;
	bi.pszDisplayName=displayname;
	bi.lpszTitle="选择要保存接收数据的文件夹";
	bi.ulFlags=BIF_EDITBOX;
	bi.lpfn=NULL;
	pidlBrowse=SHBrowseForFolder(&bi);
	if(pidlBrowse!=NULL)
	{
		SHGetPathFromIDList(pidlBrowse,path);
	}
	CString str=path;
	if(str.IsEmpty())
		return;
	m_strCurPath=str;
	UpdateData(FALSE);
}

void CSerialCommDlg::OnButtonFilebrowser() 
{
	// TODO: Add your control notification handler code here
	LPCSTR lpszPath="C:\\COMDATA";
	SetCurrentDirectory(lpszPath);
	static char BASED_CODE szFilter[]="文本文件(*.txt)|*.txt|所有文件(*.*)|*.*|";
	CFileDialog FileDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilter);
	FileDlg.m_ofn.lpstrInitialDir=lpszPath;
	if(FileDlg.DoModal()==IDOK)
	{
		CString strFileName=FileDlg.GetFileName();
		CString strFileExt=FileDlg.GetFileExt();
		CString lpstrName=FileDlg.GetPathName();
		m_strSendFilePathName=lpstrName;
		UpdateData(FALSE);
	}
}

void CSerialCommDlg::OnButtonClose() 
{
	// TODO: Add your control notification handler code here
		
	CSerialCommDlg::OnOK();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -