MFC使用串口类通讯实例

创建 MFC 对话框应用程序添加 CSerialPort 类到项目中,在对话框中添加一个 Text Control(ID:IDC_STATIC_RECEIVED_DATA),用于显示接收到的数据。一个 Button(ID:IDC_BUTTON_OPEN_PORT),用于打开串口。一个 Button(ID:IDC_BUTTON_CLOSE_PORT),用于关闭串口。

将以下 CSerialPort 类的代码添加到项目中。

CSerialPort.h

cpp 复制代码
#ifndef _CSERIALPORT_H_
#define _CSERIALPORT_H_

#include <windows.h>

class CSerialPort
{
public:
    CSerialPort();
    ~CSerialPort();

    // 打开串口
    BOOL OpenPort(UINT portNo, DWORD baudRate, BYTE parity, BYTE byteSize, BYTE stopBits);

    // 关闭串口
    BOOL ClosePort();

    // 读取数据
    DWORD ReadData(char* buffer, DWORD bufferSize);

private:
    HANDLE m_hComm; // 串口句柄
};

#endif // _CSERIALPORT_H_

CSerialPort.cpp

cpp 复制代码
#include "CSerialPort.h"

CSerialPort::CSerialPort()
    : m_hComm(INVALID_HANDLE_VALUE)
{
}

CSerialPort::~CSerialPort()
{
    ClosePort();
}

// 打开串口
BOOL CSerialPort::OpenPort(UINT portNo, DWORD baudRate, BYTE parity, BYTE byteSize, BYTE stopBits)
{
    // 构造串口名称,例如 COM1, COM2
    char portName[20];
    sprintf(portName, "\\\\.\\COM%d", portNo);

    // 打开串口
    m_hComm = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (m_hComm == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    // 配置串口参数
    DCB dcb;
    GetCommState(m_hComm, &dcb);
    dcb.BaudRate = baudRate;       // 波特率
    dcb.ByteSize = byteSize;       // 数据位
    dcb.Parity = parity;           // 校验位
    dcb.StopBits = stopBits;       // 停止位
    if (!SetCommState(m_hComm, &dcb))
    {
        CloseHandle(m_hComm);
        m_hComm = INVALID_HANDLE_VALUE;
        return FALSE;
    }

    // 设置超时
    COMMTIMEOUTS timeouts = { 0 };
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;
    SetCommTimeouts(m_hComm, &timeouts);

    return TRUE;
}

// 关闭串口
BOOL CSerialPort::ClosePort()
{
    if (m_hComm != INVALID_HANDLE_VALUE)
    {
        CloseHandle(m_hComm);
        m_hComm = INVALID_HANDLE_VALUE;
    }
    return TRUE;
}

// 读取数据
DWORD CSerialPort::ReadData(char* buffer, DWORD bufferSize)
{
    DWORD dwRead;
    if (!ReadFile(m_hComm, buffer, bufferSize, &dwRead, NULL))
    {
        return 0;
    }
    return dwRead;
}

在对话框类中实现串口通信

MyDialogDlg.h

cpp 复制代码
#include "CSerialPort.h"

#if !defined(AFX_MYDIALOGDLG_H__56A793B7_4912_43CC_8029_C4939E32DC49__INCLUDED_)
#define AFX_MYDIALOGDLG_H__56A793B7_4912_43CC_8029_C4939E32DC49__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

/////////////////////////////////////////////////////////////////////////////
// CMyDialogDlg dialog

class CMyDialogDlg : public CDialog
{
// Construction
public:
	CMyDialogDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	//{{AFX_DATA(CMyDialogDlg)
	enum { IDD = IDD_MYDIALOG_DIALOG };
		// NOTE: the ClassWizard will add data members here
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CMyDialogDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	HICON m_hIcon;

private:
    CSerialPort m_SerialPort; // 串口对象
    CString m_strReceivedData; // 接收到的数据

	// Generated message map functions
	//{{AFX_MSG(CMyDialogDlg)
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	afx_msg void OnButtonOpenPort();
	afx_msg void OnButtonClosePort();
	afx_msg void OnTimer(UINT nIDEvent);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MYDIALOGDLG_H__56A793B7_4912_43CC_8029_C4939E32DC49__INCLUDED_)

MyDialogDlg.cpp

cpp 复制代码
// MyDialogDlg.cpp : implementation file
//

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

/////////////////////////////////////////////////////////////////////////////
// CMyDialogDlg dialog

CMyDialogDlg::CMyDialogDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMyDialogDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMyDialogDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMyDialogDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMyDialogDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMyDialogDlg, CDialog)
	//{{AFX_MSG_MAP(CMyDialogDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_OPEN_PORT, OnButtonOpenPort)
	ON_BN_CLICKED(IDC_BUTTON_CLOSE_PORT, OnButtonClosePort)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMyDialogDlg message handlers

BOOL CMyDialogDlg::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
	SetTimer(1, 100, NULL); // 100ms 读取一次
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CMyDialogDlg::OnButtonOpenPort() 
{
	 if (m_SerialPort.OpenPort(1, 9600, NOPARITY, 8, ONESTOPBIT))
    {
        AfxMessageBox("串口打开成功!");
    }
    else
    {
        AfxMessageBox("串口打开失败!");
    }
	
}

void CMyDialogDlg::OnButtonClosePort() 
{
 m_SerialPort.ClosePort();
    AfxMessageBox("串口已关闭!");	
}

void CMyDialogDlg::OnTimer(UINT nIDEvent) 
{
	 if (nIDEvent == 1)
    {
        // 读取串口数据
        char buffer[1024];
        DWORD bytesRead = m_SerialPort.ReadData(buffer, sizeof(buffer) - 1);
        if (bytesRead > 0)
        {
            buffer[bytesRead] = '\0'; // 添加字符串结束符
            m_strReceivedData += buffer; // 追加到接收数据字符串
			SetDlgItemText(IDC_STATIC_RECEIVED_DATA,m_strReceivedData); 

            UpdateData(FALSE); // 更新界面
        }
    }
	
	CDialog::OnTimer(nIDEvent);
}
相关推荐
承渊政道2 小时前
C++学习之旅【实战全面解析C++类和对象】
c++·笔记·学习
懂AI的老郑2 小时前
深入理解C++中的堆栈:从数据结构到应用实践
java·数据结构·c++
胡萝卜3.02 小时前
现代C++特性深度探索:模板扩展、类增强、STL更新与Lambda表达式
服务器·开发语言·前端·c++·人工智能·lambda·移动构造和移动赋值
晚风(●•σ )2 小时前
C++语言程序设计——12 排序算法-桶排序
c++·算法·排序算法
淀粉肠kk2 小时前
【数据结构】哈希表
数据结构·c++
郝学胜-神的一滴2 小时前
Linux C++会话编程:从基础到实践
linux·运维·服务器·开发语言·c++·程序人生·性能优化
AA陈超2 小时前
LyraStarterGame_5.6 Experience系统分析
开发语言·c++·笔记·学习·ue5·lyra
历程里程碑3 小时前
C++ 8:list容器详解与实战指南
c语言·开发语言·数据库·c++·windows·笔记·list
小尧嵌入式3 小时前
C++11线程库的使用(上)
c语言·开发语言·c++·qt·算法