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

📄 monitorcomportdlg.cpp

📁 上一个版本是测试版;这个是应用版。这个版本去掉了上一个版本一些多余代码
💻 CPP
字号:
// MonitorComPortDlg.cpp : implementation file
//
//#include   <new> 
#include "stdafx.h"

#include "MonitorComPort.h"
#include "MonitorComPortDlg.h"

#include <afx.h>
#include <afxdlgs.h>
#include <errno.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define T2OLE(lpa) A2W(lpa)
/////////////////////////////////////////////////////////////////////////////
// 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()

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


/////////////////////////////////////////////////////////////////////////////
// CMonitorComPortDlg dialog

CMonitorComPortDlg::CMonitorComPortDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMonitorComPortDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMonitorComPortDlg)
	m_StrEdit = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMonitorComPortDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMonitorComPortDlg)
	DDX_Control(pDX, IDC_CHECK_HEXDISPLAY, m_ctrlHexDiaplay);
	DDX_Control(pDX, IDC_COMBO5, m_StopBitCombo);
	DDX_Control(pDX, IDC_COMBO4, m_BitDigCombo);
	DDX_Control(pDX, IDC_COMBO3, m_CompareCombo);
	DDX_Control(pDX, IDC_COMBO2, m_SpeedCombo);
	DDX_Control(pDX, IDC_COMBO_COM, m_ComPortCombo);
	DDX_Control(pDX, IDC_EDIT1, m_editMsg);
	DDX_Control(pDX, IDC_MSCOMM1, m_MSComm);
	DDX_Text(pDX, IDC_EDIT1, m_StrEdit);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMonitorComPortDlg, CDialog)
	//{{AFX_MSG_MAP(CMonitorComPortDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, OnSetComm)
	ON_BN_CLICKED(IDC_CLEAR_EDIT, OnClearEdit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMonitorComPortDlg message handlers

BOOL CMonitorComPortDlg::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_MSComm.Create(NULL,0,CRect(0,0,0,0),this,IDC_MSCOMM1);
	
	TimeToString(filename);
	fileNamePath = "D:\\TXT\\";
	m_ctrlHexDiaplay.SetCheck(1);
	m_ComPortCombo.AddString("COM1");	
	m_ComPortCombo.AddString("COM2");
	m_ComPortCombo.AddString("COM3");
	m_ComPortCombo.AddString("COM4");
	m_ComPortCombo.SetCurSel(0);
	
	m_SpeedCombo.AddString("38400");
	m_SpeedCombo.AddString("19200");
	m_SpeedCombo.AddString("9600");
	m_SpeedCombo.AddString("4800");	
	m_SpeedCombo.AddString("2400");
	m_SpeedCombo.AddString("1200");
	m_SpeedCombo.SetCurSel(5);

	m_CompareCombo.AddString("NONE");
	m_CompareCombo.AddString("ODD");
	m_CompareCombo.AddString("EVEN");
	m_CompareCombo.SetCurSel(1);

	m_BitDigCombo.AddString("6");
	m_BitDigCombo.AddString("7");
	m_BitDigCombo.AddString("8");
	m_BitDigCombo.SetCurSel(2);

	m_StopBitCombo.AddString("1");
	m_StopBitCombo.AddString("2");
	m_StopBitCombo.SetCurSel(0);
	
	if(m_MSComm.GetPortOpen())//如果串口是打开的,则行关闭串口
		m_MSComm.SetPortOpen(FALSE);
	int iCom = m_MSComm.GetCommPort();
	m_MSComm.SetCommPort(iCom);
	m_MSComm.SetInBufferSize(1024); //接收缓冲区
	m_MSComm.SetOutBufferSize(1024);//发送缓冲区
	m_MSComm.SetInputLen(0);//设置当前接收区数据长度为0,表示全部读取
	m_MSComm.SetInputMode(1);//以二进制方式读写数据
	m_MSComm.SetRThreshold(1);//接收缓冲区有1个及1个以上字符时,将引发接收数据的OnComm事件
	m_MSComm.SetSettings("9600,n,8,1");//波特率9600无检验位,8个数据位,1个停止位
	
	if(!m_MSComm.GetPortOpen()) //如果串口没有打开则打开
	{
		m_MSComm.SetPortOpen(TRUE);
	}
	else
		// 		MessageBox("串口打开!");
		AfxMessageBox("Open Serial Port Failure!");
//	m_MSComm.GetInput(); //先预读缓冲区以清除残留数据
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMonitorComPortDlg::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 CMonitorComPortDlg::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 CMonitorComPortDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
//CString CMonitorComPortDlg::GetStrFileName(const CString str)
//{
//	return &str;
//}

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

void CMonitorComPortDlg::OnCommMscomm() 
{
	// TODO: Add your control notification handler code here
	BYTE					rxdata[2048];
	CFileStatus				fs;
	COleSafeArray			safearray_inp;
	CString					fileNamePath,strtemp,fileName,strRecive,strName;
	int						iCount;
	LONG					len,k,filesize = 0;
	
	VARIANT					varint_inp;
	if(m_MSComm.GetCommEvent() == 2)
	{
		iCount = m_MSComm.GetInBufferCount();
		if(iCount > 0)
		{
			varint_inp = m_MSComm.GetInput();
			safearray_inp = varint_inp;
			len = safearray_inp.GetOneDimSize();
			for(k = 0;k < len;k++)
			{
				safearray_inp.GetElement(&k,rxdata+k);
			}
			for(k = 0;k < len;k++)
			{
				BYTE bt = *(char*)(rxdata+k);
				if(m_ctrlHexDiaplay.GetCheck())
					strtemp.Format("%02X ",bt); //将字符以十六进制方式送入临时变量strtemp存放,注意这里加入一个空隔
				else 
					strtemp.Format("%c",bt); //将字符送入临时变量strtemp存放
					
				strRecive += strtemp;
				m_StrEdit += strtemp;
			}

		}
		CreateTXTFile(fileNamePath,filename);
		file.GetStatus(fileNamePath,fs);
		inameSign = fs.m_size/1024 +1;
		if((inameSign >= 0)&&(inameSign < 3000))
		{	
			WriteFile(fileNamePath,strRecive);
		}
		else 
		{
			GetTimeString(filename);				
			CreateTXTFile(fileNamePath,filename);
			WriteFile(fileNamePath,strRecive);
			m_editMsg.SetWindowText(_T(""));
			UpdateData(TRUE);
		}
	}
	UpdateData(FALSE);

//pdateData(FALSE); //更新编辑框内容
	if(m_MSComm.GetCommEvent() == 1)
	{
		
		strtemp.Format("OK,I've received some data!\r\n");
		m_MSComm.SetOutput(COleVariant(strtemp));//发送数据
	}	
}
CString CMonitorComPortDlg::CreateTXTFile(CString &filePath, CString &fileName)
{
//	TimeToString(fileName);
	filePath = "d:\\txt\\" + fileName;
	
	CFile   file(filePath,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate);

	CArchive ar(&file,CArchive::store|CArchive::bNoFlushOnDelete);
	ar.Close();
	return filePath;

	
}

void CMonitorComPortDlg::WriteFile(CString &filePath, CString &fileStr)
{ 

	CString tempStr;
	CFileException fe;
	CFileStatus fstatus;

	GetTimeString(tempStr);
	fileStr = fileStr +"   "+ tempStr +"\r\n";

	bOpen = file.Open(filePath,CFile::modeWrite|CFile::modeNoTruncate,&fe);
	
	if(!bOpen)
	{
		fe.ThrowErrno(1,NULL);

	}
	file.SeekToEnd();
	file.Write(fileStr,fileStr.GetLength());

	
	file.GetStatus(filePath,fstatus);
	CArchive ar(&file,CArchive::store); 
	ar.Close();   
	file.Close();   
}

CString CMonitorComPortDlg::TimeToString(CString &str)
{
	CTime time = CTime::GetCurrentTime();
	CString strYear,strMonth,strDay;
	
	CString strTime = time.Format("%Y-%m-%d-%H:%M:%S");
	
	strYear = strTime.Left(4);
	strMonth = strTime.Mid(5,2);
	strDay = strTime.Mid(8,2);

	int iYear = atoi(strYear);
	int iMonth = atoi(strMonth);
	int iDay = atoi(strDay);
	str.Format("%d-%d-%d.txt",iYear,iMonth,iDay);
	return str;

}

CString CMonitorComPortDlg::GetTimeString(CString &strTime)
{
	CTime time = CTime::GetCurrentTime();
	strTime = time.Format("%Y-%m-%d-%H-%M-%S.txt");
	return strTime;
}

BOOL CMonitorComPortDlg::OnInitComm()
{
	CString strCom,strSpeed,strCompare,strBit,strStop,strTemp;
	int iCom = 0;
	try{
			m_ComPortCombo.GetWindowText(strCom);
			iCom = atoi(strCom.Right(1));
			if(m_MSComm.GetPortOpen())
			{
				m_MSComm.SetPortOpen(FALSE);
			}
			m_MSComm.SetCommPort(iCom);
	
			m_SpeedCombo.GetWindowText(strSpeed);
			m_CompareCombo.GetWindowText(strCompare);
			strCompare = strCompare.Left(1);
			m_BitDigCombo.GetWindowText(strBit);
			m_StopBitCombo.GetWindowText(strStop);
			strTemp = strSpeed +","+ strCompare +","+ strBit +"," +strStop;

			m_MSComm.SetSettings(strTemp);
			if(!m_MSComm.GetPortOpen())
			{
				m_MSComm.SetPortOpen(TRUE);
			}
			else
			{
				AfxMessageBox("Open Serial Port Failure!");
			}
			m_MSComm.GetInput(); //先预读缓冲区以清除残留数据
			AfxMessageBox("设置成功!");
			
	}
	catch (...) 
	{
		AfxMessageBox("串口初始化失败!请重新设置!");
		return FALSE;
	}
	return TRUE;
}

void CMonitorComPortDlg::OnSetComm() 
{
	// TODO: Add your control notification handler code here
	OnInitComm();
}

void CMonitorComPortDlg::OnClearEdit() 
{
	// TODO: Add your control notification handler code here
	m_editMsg.SetWindowText(_T(""));
	UpdateData(TRUE);
	
}

⌨️ 快捷键说明

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