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

📄 seriesportdlg.cpp

📁 通过CreatFile SetupComm GetCommStat等API函数来创建一个串口传输程序
💻 CPP
字号:
// SeriesPortDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SeriesPort.h"
#include "SeriesPortDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About


CSeriesPortApp theApp;
const          CM_RECEIVE=WM_USER+100;
OVERLAPPED     tOverLaped=   {0};
OVERLAPPED     wOverLaped=   {0};
OVERLAPPED     rOverLaped=   {0};
BOOL           bIsRun    =FALSE;
BOOL           bIsStop   =FALSE;

DWORD    ThreadFunction(LPVOID   pParam)
{
	DWORD  dwEvtMask,dwResult;
	tOverLaped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
	while (bIsRun)
	{
		//等待窗口事件
		WaitCommEvent(((CSeriesPortDlg*)AfxGetMainWnd())->hCom,
			&dwEvtMask,&tOverLaped);
		//如果没有事件没有信号,延时0.1秒
		dwResult=WaitForSingleObject(tOverLaped.hEvent,100);

		if (dwResult==WAIT_OBJECT_0)
		{
			if (dwEvtMask==EV_RXCHAR)
			{
				if (bIsStop)
				{
					bIsStop=FALSE;
					::PostMessage(AfxGetMainWnd()->m_hWnd,CM_RECEIVE,
						0,(LPARAM)EV_RXCHAR);
				}
			}
		}
	}
	return 0;
}

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()

/////////////////////////////////////////////////////////////////////////////
// CSeriesPortDlg dialog

CSeriesPortDlg::CSeriesPortDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSeriesPortDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSeriesPortDlg)
		// 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 CSeriesPortDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSeriesPortDlg)
	DDX_Control(pDX, IDC_EDIT, m_Edit);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSeriesPortDlg, CDialog)
	//{{AFX_MSG_MAP(CSeriesPortDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	//}}AFX_MSG_MAP
	ON_MESSAGE (CM_RECEIVE,OnReceiveData)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSeriesPortDlg message handlers

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

	hCom=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,
					0,
					NULL,
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
					NULL
					);
	
	if (hCom==INVALID_HANDLE_VALUE)
	{
		MessageBox("端口打开失败");
		
	}
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSeriesPortDlg::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 CSeriesPortDlg::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 CSeriesPortDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
void  CSeriesPortDlg::OnReceiveData(WPARAM wParam,LPARAM lParam)
{
	DWORD res,factbyte;
	memset(DataBuffer,0,1024);
	COMSTAT    rst;
	ClearCommError(hCom,&res,&rst);
	rOverLaped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);  //创建一个事件对象
	//读取数据到缓冲区
	if (ReadFile(hCom,DataBuffer,rst.cbInQue,&factbyte,&rOverLaped))
	{
		DataBuffer[rst.cbInQue]=0;
		bIsStop=FALSE;
	}
	else
	{
		res=WaitForSingleObject(rOverLaped.hEvent,5000);

	}
	bIsStop=FALSE;
	int  num=0,si=-1;
	char  str[2][1024];//分别保存文件名和内容
	for (int i=0;i<rst.cbInQue;i++)
	{
		if (DataBuffer[i]=='~')
		{
			num++;
			si=i;
			continue;
		}
		str[num][i-si-1]=DataBuffer[i];
	}
	CString Path="F:\\";
	Path+=str[0];
	Path=Path.Left(si+3);
	CFile   file(_T(Path),CFile::modeCreate|CFile::modeWrite);
	file.Write(str[1],rst.cbInQue-si);
	file.Close();
}




void CSeriesPortDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
	SetupComm(hCom,1024,1024);
	DCB  dcb;
	GetCommState(hCom,&dcb);
	dcb.BaudRate=9600;
	dcb.fBinary=TRUE;
	dcb.fParity=TRUE;
	dcb.ByteSize=8;
	dcb.Parity=ODDPARITY;
	dcb.StopBits=ONESTOPBIT;
	if (!SetCommState(hCom,&dcb))
	{
		MessageBox("设置失败","提示");
		return;
	}
	if (!SetCommMask(hCom,EV_RXCHAR|EV_TXEMPTY))
	{
		MessageBox("掩码设置失败","提示");
		return;
	}
	DWORD  param;
	hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunction,
			&param,0,&dwThreadID);
	if (hThread==INVALID_HANDLE_VALUE)
	{
		MessageBox("线程创建失败","提示",64);
		return ;
	}
	bIsRun=TRUE;
	
}

void CSeriesPortDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	DWORD  res;
	DWORD  factdata=0;
	CString   str;
	str=strPath+"~"+strText;
	wOverLaped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
	bIsStop=FALSE;
	if (WriteFile(hCom,str,str.GetLength(),&factdata,&wOverLaped))
	{
		bIsStop=TRUE;
		MessageBox("发送成功") ;
	}
	else
	{
		res=WaitForSingleObject(wOverLaped.hEvent,5000);
		if (WAIT_OBJECT_0==res)
		{
			bIsStop=TRUE;
		}
		else
			bIsStop=FALSE;
		Sleep(1000);
		
	}
	
}

void CSeriesPortDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	CFileDialog  dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
				"All Files(*.*)|*.*||",AfxGetMainWnd());
	strText="";
	if (dlg.DoModal()==IDOK)
	{
		strPath=dlg.GetFileName();
	}
	CFile  file(strPath,CFile::modeRead);
	char   read[1000];
	file.Read(read,1000);
	for (int i=0;i<file.GetLength();i++)
	{
		strText+=read[i];
	}
	m_Edit.SetWindowText(strText);
	file.Close();
	
}

⌨️ 快捷键说明

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