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

📄 mycommundlg.cpp

📁 Visual C++高级编程及其项目应用开发(含源代码)
💻 CPP
字号:
// MyCommunDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MyCommun.h"
#include "MyCommunDlg.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()

/////////////////////////////////////////////////////////////////////////////
// CMyCommunDlg dialog

CMyCommunDlg::CMyCommunDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMyCommunDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMyCommunDlg)
	m_strPortName = _T("COM1");
	m_strSend = _T("");
	m_strSendEd = _T("");
	m_dwdPaud = 9600;
	m_strData = _T("");
	//}}AFX_DATA_INIT

	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMyCommunDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMyCommunDlg)
	DDX_Control(pDX, IDC_COMBO_ODD, m_cmbOdd);
	DDX_Control(pDX, IDC_COMBO_END, m_cmbEnd);
	DDX_Control(pDX, IDC_COMBO_DATA, m_cmbData);
	DDX_Text(pDX, IDC_EDIT_NAME, m_strPortName);
	DDX_Text(pDX, IDC_EDIT_SEND, m_strSend);
	DDX_Text(pDX, IDC_EDIT_SENDED, m_strSendEd);
	DDX_Text(pDX, IDC_EDIT_PAUD, m_dwdPaud);
	DDX_CBString(pDX, IDC_COMBO_DATA, m_strData);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMyCommunDlg, CDialog)
	//{{AFX_MSG_MAP(CMyCommunDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_OPENCOM, OnBtnOpencom)
	ON_BN_CLICKED(IDC_BTN_CLOSECOM, OnBtnClosecom)
	ON_BN_CLICKED(IDC_BTN_WRITE, OnBtnWrite)
	ON_BN_CLICKED(IDC_BTN_READ, OnBtnRead)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMyCommunDlg message handlers

BOOL CMyCommunDlg::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);
		}
	}

	AfxGetApp()->GetMainWnd()->SetWindowText("串口通讯测试");

	m_cmbData.InsertString(-1, "5");
	m_cmbData.InsertString(-1, "6");
	m_cmbData.InsertString(-1, "7");
	m_cmbData.InsertString(-1, "8");
	m_cmbData.SetCurSel(3);

	m_cmbEnd.InsertString(-1,"ONESTOPBIT");
	m_cmbEnd.InsertString(-1,"ONE5STOPBITS");
	m_cmbEnd.InsertString(-1,"TWOSTOPBITS");
	m_cmbEnd.SetCurSel(0);

	m_cmbOdd.InsertString(-1,"None");
	m_cmbOdd.InsertString(-1,"Odd");
	m_cmbOdd.InsertString(-1,"Even");
	m_cmbOdd.InsertString(-1,"Mark");
	m_cmbOdd.InsertString(-1,"Space");
	m_cmbOdd.SetCurSel(0);
	
	// 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
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

/*********************************************
* 从这里开始的代码全部是用户的事件处理代码
*********************************************/

void CMyCommunDlg::OnBtnOpencom() 
{
	// TODO: Add your control notification handler code here
	DWORD dwError;  // 定义错误码的捕获变量
	DCB dcb;
	COMMTIMEOUTS TimeOuts; // 超时设置

	UpdateData();

	//if(hCom != NULL)
	//{
	//	CloseHandle(hCom);
	//}

	hCom=CreateFile(LPCSTR(m_strPortName), 
		GENERIC_READ | GENERIC_WRITE, // 允许读和写 
		0, // 独占方式
		NULL, 
		OPEN_EXISTING, //打开而不是创建
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // 重叠方式
		NULL
		);

	if(hCom == INVALID_HANDLE_VALUE)
	{
		dwError=GetLastError( );
		AfxMessageBox("打开串口出错!");
		return;
	}

	SetupComm(hCom, 1024, 1024 ); //缓冲区的大小为1024

	// 把间隔超时设为最大,把总超时设为0将导致ReadFile立即返回
	TimeOuts.ReadIntervalTimeout = MAXDWORD; 
	TimeOuts.ReadTotalTimeoutMultiplier = 0; 
	TimeOuts.ReadTotalTimeoutConstant = 0; 
	TimeOuts.WriteTotalTimeoutMultiplier = 0; 
	TimeOuts.WriteTotalTimeoutConstant = 0;

	SetCommTimeouts(hCom, &TimeOuts); // 设置超时

	PurgeComm(hCom, PURGE_RXABORT | PURGE_RXCLEAR);

	GetCommState(hCom, &dcb);

	dcb.BaudRate = m_dwdPaud; // 波特率
	dcb.ByteSize = atoi(LPCSTR(m_strData)); // 设置停止位
	int i;
	i =m_cmbOdd.GetCurSel(); 
	// 奇偶校验位和停止位,用对应的索引号即可。这也正好是对应常量的值
	dcb.Parity = m_cmbOdd.GetCurSel(); 
	dcb.StopBits = m_cmbEnd.GetCurSel();

	// 设置通信设备
	SetCommState(hCom, &dcb);	
}

void CMyCommunDlg::OnBtnClosecom() 
{
	// TODO: Add your control notification handler code here
	CloseHandle(hCom);
}

void CMyCommunDlg::OnBtnWrite() 
{
	// TODO: Add your control notification handler code here
	DWORD	nToWrite, nWritten;
	DWORD	dwWrite;

	OVERLAPPED	osWrite;

	CString strTem;
	
	UpdateData();
	nToWrite = m_strSend.GetLength();

	//ZeroMemory(&osWrite, sizeof(osWrite));
	memset(&osWrite, 0, sizeof(osWrite));
	osWrite.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	if(osWrite.hEvent == NULL)
	{
		AfxMessageBox("创建事件对象失败!");
		return;
	}

	dwWrite = WriteFile(hCom, m_strSend.GetBuffer(nToWrite), nToWrite, &nWritten, &osWrite);
	if(!dwWrite && (GetLastError()==ERROR_IO_PENDING) )
	{
		// 等待,函数的参数设置为TRUE,相当于调用WaitForSingleObject函数
		GetOverlappedResult(hCom, &osWrite, &nWritten, TRUE);
		
		strTem.Format("%d", nWritten);
		m_strSendEd = m_strSend + "\r\n" +"写入的字节数为:" +strTem;

		UpdateData(FALSE);
	}
	else
	{
		AfxMessageBox("写串口失败!");
		return;
	}

	m_strSend.ReleaseBuffer();
	CloseHandle(osWrite.hEvent);
}

void CMyCommunDlg::OnBtnRead() 
{
	// TODO: Add your control notification handler code here
	CString strRead;
	CString strTem;

	OVERLAPPED osRead;
	DWORD nToRead, nHaveRead;
	DWORD dwErrorFlags, dwRead;
	
	COMSTAT ComStat;

	//ZeroMemory(&osRead, sizeof(osRead));
	memset(&osRead, 0, sizeof(osRead));
	osRead.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	if(osRead.hEvent == NULL)
	{
		AfxMessageBox("创建事件对象失败!");
		return ;
	}

	ZeroMemory(&ComStat, sizeof(ComStat));
	if(!ClearCommError(hCom, &dwErrorFlags, &ComStat))
	{
		PurgeComm(hCom, PURGE_RXABORT | PURGE_RXCLEAR);
		return;
	}

	nToRead = ComStat.cbInQue;
	if(nToRead <= 0)
	{
		AfxMessageBox("输入缓存没有数据!");
		return;
	}

	char sBuffer[1024];
	memset(&sBuffer, 0, 1024);

	dwRead = ReadFile(hCom, &sBuffer, nToRead, &nHaveRead, &osRead);
	if(dwRead)
	{
		GetOverlappedResult(hCom, &osRead,&nHaveRead,TRUE);
		strTem.Format("%d", nHaveRead);
		strRead = sBuffer;
		m_strSendEd = strRead + "\r\n" +"读到的字节数为:" + strTem;

		UpdateData(FALSE);
		/*if(GetLastError() == ERROR_IO_PENDING)
		{
			// 等待,函数的参数设置为TRUE,相当于调用WaitForSingleObject函数
			while(!GetOverlappedResult(hCom, &osRead,&nHaveRead,TRUE))
			{
				if(GetLastError() == ERROR_IO_INCOMPLETE) 
				{
					continue; 
				}
			}
			strTem.Format("%d", nHaveRead);
			strRead = sBuffer;
			m_strSendEd = strRead + "\r\n" +"读到的字节数为:" + strTem;

			UpdateData(FALSE);
		}
		else
		{
			AfxMessageBox("读串口失败!");
			AfxMessageBox(sBuffer);
			return;
		}*/
	}

	CloseHandle(osRead.hEvent);
}

⌨️ 快捷键说明

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