借助开源文件:Com_class.h
程序实例:http://pan.baidu.com/s/1qWHUQmS
使用步骤: 1.包含Com_class.h头文件
2.
#include "Com_class.h"
class CComDlgDlg : public CDialog
{
// Construction
public:
LRESULT On_Receive(WPARAM wp, LPARAM lp);
_thread_com com2;
CComDlgDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CComDlgDlg)
enum { IDD = IDD_COMDLG_DIALOG };
CString m_e;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CComDlgDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CComDlgDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
virtual void OnOK();
afx_msg void OnButton1();
afx_msg void OnButton2();
afx_msg void OnButton3();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_COMDLGDLG_H__75BDFED3_C096_4C40_AB56_E631ECD7434D__INCLUDED_)
3.添加消息映射
BEGIN_MESSAGE_MAP(CComDlgDlg, CDialog) //{{AFX_MSG_MAP(CComDlgDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3) //}}AFX_MSG_MAP ON_MESSAGE(ON_COM_RECEIVE, On_Receive) END_MESSAGE_MAP()
4.添加重载函数
LRESULT CComDlgDlg::On_Receive(WPARAM wp, LPARAM lp) { int len; char str[100]; len = com2.read(str, 100); if(len > 0) { char com_str[10]; strcpy(com_str, "COM"); ltoa((long)wp, com_str + 3, 10); // WPARAM 保存端口号 m_e += com_str; m_e += " : "; m_e += str; m_e += "\r\n"; UpdateData(false); } return 0; }
5.打开串口
void CComDlgDlg::OnButton1() { if(!com2.open(5))//默认是9600 调用不同的OPEN可以调节波特率 MessageBox("open fail", "COM5", MB_OK); else com2.set_hwnd(m_hWnd); }
6.发送数据
void CComDlgDlg::OnButton3() { char buff[100]; // TODO: Add your control notification handler code here // com2<<1; buff[0]=0x55; com2.write(buff,1); }
7.关闭串口
void CComDlgDlg::OnButton2() { com2.close(); }