📄 testmscomdlg.cpp
字号:
// TestMSComDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TestMSCom.h"
#include "TestMSComDlg.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()
/////////////////////////////////////////////////////////////////////////////
// CTestMSComDlg dialog
CTestMSComDlg::CTestMSComDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTestMSComDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTestMSComDlg)
m_SendStr = _T("");
m_hPort = NULL;
m_pCommThread = NULL;
m_bExitThread = FALSE;
m_FileName = _T("");
m_num = 0;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTestMSComDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTestMSComDlg)
DDX_Control(pDX, IDC_PROGRESS, m_Progress);
DDX_Control(pDX, IDC_PROG, m_Prog);
DDX_Control(pDX, IDC_OPEN_PORT, m_OpenPortBNT);
DDX_Control(pDX, IDC_CLOSE_PORT, m_ClosePortBNT);
DDX_Control(pDX, IDC_BNT_SEND, m_SendBNT);
DDX_Control(pDX, IDC_EDIT_REC, m_Edit);
DDX_Text(pDX, IDC_EDIT_SEND, m_SendStr);
DDX_Text(pDX, IDC_FILENAME, m_FileName);
DDX_Text(pDX, IDC_NUM, m_num);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTestMSComDlg, CDialog)
//{{AFX_MSG_MAP(CTestMSComDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_SET_PORT, OnSetPort)
ON_BN_CLICKED(IDC_OPEN_PORT, OnOpenPort)
ON_MESSAGE(WM_RECVDATA,OnRecvData)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_BNT_CLEAR, OnBntClear)
ON_BN_CLICKED(IDC_CLOSE_PORT, OnClosePort)
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_BNT_SEND, OnBntSend)
ON_BN_CLICKED(IDC_PROG, OnProg)
ON_BN_CLICKED(IDC_OPEN_HEX_FILE, OnOpenHexFile)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTestMSComDlg message handlers
BOOL CTestMSComDlg::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_SendBNT.EnableWindow(FALSE);
m_ClosePortBNT.EnableWindow(FALSE);
m_Prog.EnableWindow(FALSE);
m_Progress.SetRange(0,1000);
m_Progress.SetPos(1000);
m_Progress.SetStep(10);
// UpDateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
void CTestMSComDlg::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 CTestMSComDlg::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 CTestMSComDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CTestMSComDlg::OnSetPort()
{
// TODO: Add your control notification handler code here
PortSetting.DoModal();
}
void CTestMSComDlg::OnOpenPort()
{
// TODO: Add your control notification handler code here
extern int m_nDataBits;
extern int m_nStopBits;
extern int m_nParity;
extern int m_nBaud;
extern int m_nPort;
if(m_hPort)
{
MessageBox("串口已经打开!");
return;
}
//设置结束接收线程标志
m_bExitThread = FALSE;
CString sPort;
sPort.Format(_T("COM%d"),m_nPort+1);
m_hPort = CreateFile(sPort,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);
if(m_hPort == INVALID_HANDLE_VALUE)
{
MessageBox("打开串口失败!");
m_hPort = NULL;
return;
}
m_OpenPortBNT.EnableWindow(FALSE);
m_SendBNT.EnableWindow(TRUE);
m_ClosePortBNT.EnableWindow(TRUE);
m_Prog.EnableWindow(TRUE);
DCB ComDCB;
ComDCB.DCBlength = sizeof(DCB);
switch(m_nBaud)
{
case 0 : ComDCB.BaudRate = 1200;break;
case 1 : ComDCB.BaudRate = 2400;break;
case 2 : ComDCB.BaudRate = 4500;break;
case 3 : ComDCB.BaudRate = 9600;break;
default:break;
}
switch(m_nDataBits)
{
case 0 : ComDCB.ByteSize = 4;break;
case 1 : ComDCB.ByteSize = 5;break;
case 2 : ComDCB.ByteSize = 6;break;
case 3 : ComDCB.ByteSize = 7;break;
case 4 : ComDCB.ByteSize = 8;break;
default:break;
}
switch(m_nParity)
{
case 0 : ComDCB.Parity = EVENPARITY;break;
case 1 : ComDCB.Parity = MARKPARITY;break;
case 2 : ComDCB.Parity = NOPARITY;break;
case 3 : ComDCB.Parity = ODDPARITY;break;
case 4 : ComDCB.Parity = SPACEPARITY;break;
default:break;
}
switch(m_nStopBits)
{
case 0 : ComDCB.StopBits= ONESTOPBIT;break;
case 1 : ComDCB.StopBits = ONE5STOPBITS;break;
case 2 : ComDCB.StopBits= TWOSTOPBITS;break;
default:break;
}
SetCommState(m_hPort,&ComDCB);
//启动接收线程
m_pCommThread = AfxBeginThread(lpCommThreadProc, this);
if(m_pCommThread)
m_pCommThread->m_bAutoDelete = TRUE;
else
{
MessageBox("启动接收线程失败!");
CloseHandle(m_hPort);
m_hPort = NULL;
return;
}
}
void CTestMSComDlg::OnRecvData(WPARAM wp,LPARAM lp)
{
}
UINT CTestMSComDlg::lpCommThreadProc(LPVOID lpParam)
{
CTestMSComDlg *pWnd = (CTestMSComDlg*) lpParam;
// BYTE RecvBuf[1024];
unsigned char *RecvBuf=new unsigned char[1024];
OVERLAPPED overlapped;
DWORD dwEvtMask = 0;
DWORD dwError,dwReadCount=0;
DWORD dwReturnCount;
COMSTAT cs;
memset(&overlapped,0,sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
SetCommMask(pWnd->m_hPort, EV_RXCHAR);
while(!pWnd->m_bExitThread)
{
WaitCommEvent(pWnd->m_hPort, &dwEvtMask, NULL);
if(dwEvtMask & EV_RXCHAR)
{
//获取串口状态
ClearCommError(pWnd->m_hPort, &dwError, &cs);
dwReadCount = cs.cbInQue; //串行设备收到的字节数
if(dwReadCount <= 0) continue;
BOOL bReadStat = ReadFile(pWnd->m_hPort, RecvBuf, dwReadCount, &dwReturnCount, &overlapped);
pWnd->TransferRecData(RecvBuf, dwReturnCount);
}
}
CloseHandle(overlapped.hEvent);
PurgeComm(pWnd->m_hPort, PURGE_TXABORT|PURGE_RXABORT|PURGE_RXCLEAR|PURGE_TXCLEAR); //进行清空串口缓冲区等操作
return 0;
}
//void CTestMSComDlg::TransferRecData(BYTE* Buf, int Len)
void CTestMSComDlg::TransferRecData(unsigned char* Buf, int Len)
{
for(int i=0; i<Len; i++)
{
m_RecvBuf[i] = Buf[i];
CString str;
if(Buf[i]<=0x0F)
{
str.Format("%x",m_RecvBuf[i]);
str = "0" + str;
m_strREC += str + " ";
m_Edit.SetWindowText(m_strREC);
int nFirstVisible = m_Edit.GetLineCount()-6;
if (nFirstVisible > 0)
{
m_Edit.LineScroll(nFirstVisible, 0);
}
}
else
{
str.Format("%x",m_RecvBuf[i]);
m_strREC+=str+" ";
m_Edit.SetWindowText(m_strREC);
int nFirstVisible = m_Edit.GetLineCount()-6;
if (nFirstVisible > 0)
{
m_Edit.LineScroll(nFirstVisible, 0);
}
}
int nLength= m_Edit.GetWindowTextLength();
m_Edit.SetSel(nLength,nLength,FALSE);
}
}
void CTestMSComDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnTimer(nIDEvent);
}
void CTestMSComDlg::OnBntClear()
{
// TODO: Add your control notification handler code here
m_Edit.SetWindowText("");
m_strREC="";
}
void CTestMSComDlg::OnClosePort()
{
// TODO: Add your control notification handler code here
if(m_hPort == NULL)
{
MessageBox("串口已经关闭!");
return;
}
m_OpenPortBNT.EnableWindow(TRUE);
m_ClosePortBNT.EnableWindow(FALSE);
m_Prog.EnableWindow(FALSE);
m_SendBNT.EnableWindow(FALSE);
//设置结束接收线程标志
m_bExitThread = TRUE;
//使串口接收线程中的WaitCommEvent()函数返回
SetCommMask(m_hPort, 0);
//等待接收线程结束
WaitForSingleObject(m_pCommThread->m_hThread, INFINITE);
m_pCommThread = NULL;
//关闭串口
CloseHandle(m_hPort);
m_hPort = NULL;
}
HBRUSH CTestMSComDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
if (nCtlColor==CTLCOLOR_STATIC)
{
pDC->SetTextColor(RGB(90,0,90));
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
void CTestMSComDlg::OnBntSend()
{
// TODO: Add your control notification handler code here
OVERLAPPED m_osWrite;
BOOL bResult = FALSE;
DWORD length = 1;
DWORD dwErrorFlags;
char* SendBuf;
UpdateData(TRUE);
int nlength = m_SendStr.GetLength();
SendBuf = new char[nlength];
SendBuf = m_SendStr.GetBuffer(0);
COMSTAT ComStat;
m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_osWrite.Offset = 0;
m_osWrite.OffsetHigh = 0;
ClearCommError(m_hPort, &dwErrorFlags, &ComStat);
bResult = WriteFile(m_hPort,SendBuf,nlength,&length,&m_osWrite);
/* unsigned char *a = new unsigned char[1];
a[0]=237;
CString ss;
ss.Format("%s",a);
WriteFile(m_hPort,a,1,&length,&m_osWrite);*/
}
void CTestMSComDlg::OnProg()
{
// TODO: Add your control notification handler code here
OVERLAPPED m_osWrite;
DWORD length = 1;
COMSTAT ComStat;
DWORD dwErrorFlags;
char* SendBuf = new char[1];
CStdioFile m_File; //读.HEX文件用
CString str;
int pos=0;
unsigned short prodata;
m_Progress.SetPos(0);
m_num=0;
if(m_FileName=="")
{
MessageBox("请先选择要下载的文件!");
CString str;
CFileDialog fileDialog(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"*.hex|*.HEX",NULL);
fileDialog.m_ofn.lpstrTitle = "选择需要下载的*.Hex目标文件";
fileDialog.DoModal();
str=fileDialog.GetPathName();
m_FileName=str;
};
m_File.Open(m_FileName,CFile::modeRead);
m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_osWrite.Offset = 0;
m_osWrite.OffsetHigh = 0;
ClearCommError(m_hPort, &dwErrorFlags, &ComStat);
while(m_File.ReadString(str)) // 每次循环读一行
{
if(Char2ToByte(str.Mid(1,2))!=0) // 判是否是最后一行
{
//addr = Char4ToByte(str.Mid(3,4)); // 取该行数据的下载首地址
for(int i=9;i<=Char2ToByte(str.Mid(1,2))*2+7;i+=2)
{
prodata = (BYTE)Char2ToByte(str.Mid(i,2)); //取下载的数据,每次取一个字节 0~255
///****需做修改的部分****///
SendBuf[0] = prodata;
WriteFile(m_hPort,SendBuf,1,&length,&m_osWrite);
///*********************///
m_num++; // 下载字节个数加1
}
}
}
m_Progress.SetPos(1000);
BeepOk();
UpdateData(FALSE);
}
void CTestMSComDlg::OnOpenHexFile()
{
// TODO: Add your control notification handler code here
CString str;
CFileDialog fileDialog(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"*.hex|*.HEX",NULL);
fileDialog.m_ofn.lpstrTitle = "选择需要下载的*.Hex目标文件";
fileDialog.DoModal();
str=fileDialog.GetPathName();
m_FileName=str;
UpdateData(FALSE);
}
int CTestMSComDlg::Char2ToByte(CString str)
{
char h0,l0;
char* pChar;
int value;
pChar=new char[2];
pChar=str.GetBuffer(0);
h0=pChar[0];//高4位
l0=pChar[1];//低4位
if(l0>='0'&&l0<='9')
l0=l0-'0';
else if(l0>='A' && l0<='F')
l0=l0-'A'+0xa;
if(h0>='0'&&h0<='9')
h0=h0-'0';
else if(h0>='A'&&h0<='F')
h0=h0-'A'+0xa;
value=h0*16+l0;
return value;
}
void CTestMSComDlg::BeepOk()
{
Beep(2000,30);
Sleep(100);
Beep(2000,30);
Sleep(100);
Beep(2000,30);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -