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

📄 testdlg.cpp

📁 本代码实现了类似于超级终端的功能
💻 CPP
字号:
// TestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "process.h"
#include "Test.h"
#include "TestDlg.h"
#include "comm.h"

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

extern HANDLE m_AbortEvent;
extern HANDLE m_hComDev;   //串口设备句柄
extern OVERLAPPED m_OverlappedRead,m_OverlappedWrite;//读重叠方式
extern UINT ReadThreadFun(LPVOID lparam);
extern UINT WriteFunC(LPVOID lParam);
/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CTestDlg dialog

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

void CTestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTestDlg)
	DDX_Control(pDX, IDC_LIST_WRITE, m_ctlWrite);
	DDX_Control(pDX, IDC_LIST_READ, m_ctlRead);
	DDX_Control(pDX, IDC_COMBO_TYPE, m_ctlType);
	DDX_Text(pDX, IDC_EDIT_WRITE, m_strWrite);
	DDX_Text(pDX, IDC_EDIT_BAUD, m_dwBaud);
	DDX_Text(pDX, IDC_EDIT_BYTES, m_dwBytes);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTestDlg, CDialog)
	ON_MESSAGE(WM_READ_ERROR,OnReadError)
	ON_MESSAGE(WM_ABORT,OnUserAbort)
	ON_MESSAGE(WM_RECEIVED,OnReceived)
	ON_MESSAGE(WM_WRITE_ERROR,OnWriteError)
	ON_MESSAGE(WM_WRITE_COMPLETE,OnWriteComplete)
	//{{AFX_MSG_MAP(CTestDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_OPEN, OnOpen)
	ON_BN_CLICKED(IDC_CLOSE, OnClose)
	ON_BN_CLICKED(IDC_READ, OnRead)
	ON_BN_CLICKED(IDC_WRITE, OnWrite)
	ON_BN_CLICKED(IDC_ABORT, OnAbort)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestDlg message handlers

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

	GetDlgItem(IDC_ABORT)->EnableWindow(FALSE);
	GetDlgItem(IDC_WRITE)->EnableWindow(FALSE);
	GetDlgItem(IDC_READ)->EnableWindow(FALSE);
	GetDlgItem(IDC_CLOSE)->EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_WRITE)->EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_BYTES)->EnableWindow(FALSE);
	SetDlgItemInt(IDC_EDIT_BAUD,9600,FALSE);

	
	m_hComDev = NULL;
	m_ctlType.AddString("COM1");
	m_ctlType.AddString("COM2");
	m_ctlType.SetCurSel(0);
	
	
	m_AbortEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CTestDlg::OnOpen() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	int nType;
	if (m_ctlType.GetCurSel() == 0)
	{
		nType = 1;
	}
	else
		nType = 2;
	if (OpenDevice(nType,m_dwBaud) == FALSE)
	{
		AfxMessageBox(_T("打开串口失败"));
		return;
	}
	GetDlgItem(IDC_CLOSE)->EnableWindow(TRUE);
	GetDlgItem(IDC_EDIT_WRITE)->EnableWindow(TRUE);
	GetDlgItem(IDC_WRITE)->EnableWindow(TRUE);
	//GetDlgItem(IDC_READ)->EnableWindow(TRUE);
	GetDlgItem(IDC_ABORT)->EnableWindow(TRUE);

	//开辟监听线程
	READPARAM *pReadparam = new READPARAM;
	pReadparam->hWnd = m_hWnd;
	//pReadparam->dwLength = m_dwBytes;
	//pReadparam->pDataRead = m_pDataRead;

	CWinThread * pReadThread = AfxBeginThread(ReadThreadFun,pReadparam,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
	if (!DuplicateHandle(GetCurrentProcess(),pReadThread->m_hThread,GetCurrentProcess(),&hReadThread,0,FALSE,DUPLICATE_SAME_ACCESS))
	{
		AfxMessageBox(_T("复制句柄失败"));
		return;
	}
	ResumeThread(pReadThread->m_hThread);

	
}

void CTestDlg::OnClose() 
{
	// TODO: Add your control notification handler code here
	SetEvent(m_AbortEvent);
	if (CloseDevice()!=0)
	{
		AfxMessageBox(_T("关闭设备成功!"));
	}
}

void CTestDlg::OnRead() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	m_pDataRead = new BYTE[m_dwBytes];
	READPARAM *pReadparam = new READPARAM;
	pReadparam->hWnd = m_hWnd;
	pReadparam->dwLength = m_dwBytes;
	pReadparam->pDataRead = m_pDataRead;

	CWinThread * pReadThread = AfxBeginThread(ReadThreadFun,pReadparam,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
	if (!DuplicateHandle(GetCurrentProcess(),pReadThread->m_hThread,GetCurrentProcess(),&hReadThread,0,FALSE,DUPLICATE_SAME_ACCESS))
	{
		AfxMessageBox(_T("复制句柄失败"));
		return;
	}
	ResumeThread(pReadThread->m_hThread);
	


}

void CTestDlg::OnWrite() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	DWORD dwLenth = m_strWrite.GetLength();
	if (!dwLenth)
	{
		AfxMessageBox("No DATA");
		return;
	}
	WRITEPARAM *pWriteParam = new WRITEPARAM;
	pWriteParam->dwLength = dwLenth+1;
	pWriteParam->hWnd = m_hWnd;
	pWriteParam->pbyData = new BYTE[dwLenth+1];

	memset(pWriteParam->pbyData,0,dwLenth);
	memcpy(pWriteParam->pbyData,(LPCTSTR)m_strWrite,dwLenth);

	if (1)
	{
		pWriteParam->pbyData[dwLenth] = 0x0D;
		//pWriteParam->pbyData[dwLenth-1] = 0x00;
		//pWriteParam->dwLength +=1;
	}
	


	CWinThread *pWriteThread = AfxBeginThread(WriteFunC,pWriteParam);


}

void CTestDlg::OnAbort() 
{
	// TODO: Add your control notification handler code here
	if (m_AbortEvent == NULL)
	{
		AfxMessageBox("ERROR");
		return;
	}
	SetEvent(m_AbortEvent);
}
void CTestDlg::OnReadError(WPARAM wParam,LPARAM lParam)
{
	AfxMessageBox(_T(" 读串口发生错误"));
}
void CTestDlg::OnUserAbort(WPARAM wParam,LPARAM lParam)
{
	if (hReadThread != INVALID_HANDLE_VALUE)
	{
		WaitForSingleObject(hReadThread,INFINITE);

	}
	AfxMessageBox(_T("中止操作成功"));
}
void CTestDlg::OnReceived(WPARAM wParam,LPARAM lParam)
{
	//CString strReceiv;
	
	
	BYTE * pbyData = new BYTE[lParam+1];
	memcpy(pbyData,(char *)wParam,lParam);
	pbyData[lParam] = 0;
	m_ctlRead.AddString((LPCTSTR)pbyData); 
	UpdateData(FALSE);
	delete []pbyData;
	//delete []m_pDataRead;

}
void CTestDlg::OnWriteError()
{
	AfxMessageBox(_T("写串口错误"));
}

void CTestDlg::OnWriteComplete()
{
	AfxMessageBox(_T("写串口完成"));
}


//////////////////////////////////////////////////////////////////////////
//读串口线程工作函数
//

UINT ReadThreadFun(LPVOID lparam)
{
	READPARAM * pReadParam = (READPARAM *)lparam;
	OVERLAPPED ov;
    memset(&ov,0,sizeof(ov));
    ov.hEvent = CreateEvent( 0,true,0,0);

    HANDLE arHandles[2];
    arHandles[0] = m_AbortEvent;
	char szBuf[1024];

	SetCommMask( m_hComDev,EV_RXCHAR);

    DWORD dwWait,dwEventMask,dwBytesRead,dwBytesReadTotal;
    //SetEvent(apThis->m_hThreadStarted);
    while ( 1 )
    {
        
        BOOL abRet = ::WaitCommEvent(m_hComDev,&dwEventMask, &ov) ;
        if ( !abRet )
        {
            
            ASSERT( GetLastError () == ERROR_IO_PENDING);
        }

        arHandles[1] = ov.hEvent ;
        dwBytesReadTotal = 0;
        dwWait = WaitForMultipleObjects (2,arHandles,FALSE,INFINITE);
        switch ( dwWait )
        {
        case WAIT_OBJECT_0:
            {
                //PostMessage(pReadParam->hWnd,WM_ABORT,0,0);
				::_endthreadex(1);
				break;
            }
        case WAIT_OBJECT_0 + 1:
            {
                DWORD dwMask;

				GetCommMask(m_hComDev,&dwMask);
                
				if ( dwMask & EV_TXEMPTY )
				{
					TRACE("Data sent");
					ResetEvent ( ov.hEvent );
					continue;
                }
                else  
                {
					//read data here and reset ov.hEven
					
					do
					{
						ReadFile( m_hComDev,szBuf,sizeof(szBuf),&dwBytesRead,&ov);
						dwBytesReadTotal += dwBytesRead;
						//GetOverlappedResult(m_hComDev,&ov,&dwBytesRead1,FALSE);

					}while (dwBytesRead > 0 );
					ResetEvent(ov.hEvent);
					
					if (dwBytesReadTotal != 0)
					{
						PostMessage(pReadParam->hWnd,WM_RECEIVED,(WPARAM)szBuf,dwBytesReadTotal);
					}
					
                }//else
				
            }
        }//switch
    }//while
return 0;
}


////////////////////////////////////////////////////////////////////////////
//写串口工作者线程
//
UINT WriteFunC(LPVOID lParam)
{
	WRITEPARAM * pWriteParam = (WRITEPARAM *)lParam;
	HWND hWnd = pWriteParam->hWnd;
	DWORD dwLength = pWriteParam->dwLength;
	BYTE *pbyData = new BYTE[dwLength];
	memcpy(pbyData,pWriteParam->pbyData,dwLength);
	delete lParam;

	DWORD  dwBytesWrite ;
	
	dwBytesWrite = WriteComm(pbyData,dwLength);
	if (dwBytesWrite == -1)
	{
		PostMessage(hWnd,WM_ABORT,0,0);
		return -1;
	}
	else if(dwBytesWrite == 0)
	{
		PostMessage(hWnd,WM_WRITE_ERROR,0,0);
		return 1;
	}
	else
	{
		PostMessage(hWnd,WM_WRITE_COMPLETE,0,0);
		return 0;
	}


}

⌨️ 快捷键说明

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