comrhdlg.cpp

来自「vc实现的一个串口通讯例子」· C++ 代码 · 共 345 行

CPP
345
字号
// ComRhDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ComRh.h"
#include "ComRhDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define		TIMER_ID		1001
/////////////////////////////////////////////////////////////////////////////
// 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)
	public:
	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)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CComRhDlg dialog

CComRhDlg::CComRhDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CComRhDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CComRhDlg)
		// 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 CComRhDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CComRhDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CComRhDlg, CDialog)
	//{{AFX_MSG_MAP(CComRhDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CComRhDlg message handlers

BOOL CComRhDlg::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_hCom = INVALID_HANDLE_VALUE;
	if( !InitCom(1, CBR_9600) )
		return FALSE;

	SetTimer(TIMER_ID, 100, NULL);	//设置定时器,每隔100毫秒读一次串口。
/////////////////////////////////////////////////////
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

/////////////////////////////////////////////////////////////
//打开并初始化串口
//参数com为串口号,baud为波特率。
BOOL CComRhDlg::InitCom(int com, DWORD baud)
{
	COMMTIMEOUTS   timeout;
	DCB dcb;
	BOOL result;
	int temp=0;
	char strCom[20] = "\\\\.\\com";
	char buffer[20];
	
	_itoa(com , buffer , 10);
	strcat( strCom , buffer );
	
	m_hCom = CreateFile(strCom, GENERIC_READ | GENERIC_WRITE,
		0, NULL, OPEN_EXISTING, NULL , NULL);
	if( m_hCom == INVALID_HANDLE_VALUE ) 
	{
		DWORD dwError = GetLastError();
		
		if (dwError == ERROR_ACCESS_DENIED)//已经打开
		{
			AfxMessageBox( "端口已被占用!请退出程序" , MB_OK , 0 );				
			return FALSE;
		}
		
		AfxMessageBox( "端口不存在或已坏!请退出程序" , MB_OK , 0 );
		
		return FALSE;
	}
	
	result=SetupComm( m_hCom , 512 , 512 );
	ASSERT(result);
	if(!result) return FALSE;
	
	result = PurgeComm( m_hCom , PURGE_TXCLEAR|PURGE_RXCLEAR );
	ASSERT( result );
	if( !result ) return FALSE;
	
	result = GetCommState( m_hCom , &dcb );
	ASSERT(result);
	if(!result) return FALSE;
	
	dcb.Parity = NOPARITY;
	dcb.BaudRate = baud;
	dcb.StopBits = ONESTOPBIT;
	dcb.ByteSize = 8;
	
	result = SetCommState( m_hCom , &dcb );
	ASSERT(result);
	if(!result) return FALSE;
	
	result=GetCommTimeouts( m_hCom ,  &timeout );
	ASSERT(result);
	
	if(!result) return FALSE;
	
	timeout.ReadIntervalTimeout=MAXDWORD;
	timeout.ReadTotalTimeoutMultiplier=0;
	timeout.ReadTotalTimeoutConstant=0;
	
	timeout.WriteTotalTimeoutMultiplier=0;
	timeout.WriteTotalTimeoutConstant=0;
	
	result=SetCommTimeouts( m_hCom , &timeout );
	ASSERT(result);
	if(!result) return FALSE;
	
	return TRUE;
}


//////////////////////////////////////////////
//读取串口数据,并判断所读的数据
//然后调用WriteData函数,将数据发送到串口。
void CComRhDlg::ReadData()
{

	if(m_hCom == INVALID_HANDLE_VALUE)
		return;
	DWORD nRead = 0;

	BYTE	recBuf[512];//接收数据缓冲区
	memset(recBuf, 0, sizeof(recBuf));

	BYTE	sendBuf[512];//发送数据缓冲区
	memset(sendBuf, 0, sizeof(sendBuf));

	PurgeComm( m_hCom , PURGE_TXCLEAR|PURGE_RXCLEAR );

	ReadFile( m_hCom , (char *)recBuf , 512 ,&nRead , NULL);//读串口

	if(nRead != 0)
	{
///////////////////////////////////////////////////////////
//下面是对收到的数据进行分析,然后确定发送的内容
//发送内容放到sendBuf中,
		if(recBuf[0] == 0x06)
		{
			sendBuf[0] = 0x15;
			WriteData((char *)sendBuf, 1);
		}
//		else if( (recBuf[0] == 0x53)
//					&& (recBuf[1] = 0x55)
//						.... )
//		{
//			....
//			....
//		}
///////////////////////////////////////////////////////////
			
	}
}

/////////////////////////////////////////////////////////////
//串口写操作
//将长度为len的tmpStr发到串口上。
void CComRhDlg::WriteData(char *tmpStr, int len)
{
	if(m_hCom == INVALID_HANDLE_VALUE)
		return;

	DWORD nWrite = 0;

	PurgeComm( m_hCom , PURGE_TXCLEAR|PURGE_RXCLEAR );
	Sleep(100);

	WriteFile(m_hCom, tmpStr, len , &nWrite, NULL);//写串口

	if(nWrite != len)
	{
		AfxMessageBox("写数据失败!");
	}
}



void CComRhDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	///////////////////////////////////////////////
	//定时对串口进行读操作
	if( nIDEvent == TIMER_ID )
	{
		ReadData();
	}
	///////////////////////////////////////////////

	CDialog::OnTimer(nIDEvent);
}

BOOL CComRhDlg::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	KillTimer(TIMER_ID);

	if(m_hCom != INVALID_HANDLE_VALUE)
		CloseHandle(m_hCom);

	return CDialog::DestroyWindow();
}

⌨️ 快捷键说明

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