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

📄 +

📁 Visual C++串口通信开发入门与编程实践
💻
📖 第 1 页 / 共 2 页
字号:
CConfigDlg::CConfigDlg(CWnd *pParent, DCB dcb): CDialog(CConfigDlg
  ::IDD, pParent)
{
  m_dcb = dcb;
}
CString strTemp;
strTemp.Format("%d", m_dcb.BaudRate); //显示在对话框中
((CComboBox*)GetDlgItem(IDqBAUDRATECOMBO))->SelectString(0,
  strTemp);
((CComboBox*)GetDlgItem(IDC - PARIIYCOMBO))->SetCurSel
  (m_dcb.Parity);
((CComboBox*)GetDlgItem(IDC_STOPBITSCOMBO))->SetCurSel
  (m_dcb.StopBits);
strTemp.Format("%d", m_dcb.ByteSize);
((CComboBox*)GetdlgItem(IDC_DATABITSCOMBO))->SelectString(0,
  strTemp);
m_hComm=NULL;
  m_ov.Offset=0;
  m_ov.OffsetHigh=0;
  m_ov.hEvent=NULL;
  m_hWriteEvent"NULL;
  m_ShutdownEvent=NULL;
  m_szWriteBuffer=NULL;
  m_bThreadAlive=FALSE;
do
{ SetEvent(m_hShutdownEvent);
  }while (m_bThreadAlive);
  TRACE("Thread ended\n");
  delete [] m_szWriteBuffer;
UINT portnr,  // portnumber (1..4)
UINT baud,  // baudrate
char parity,  // parity
UINT databits,  // databits
UINT stopbits,  // stopbits
DWORD dwCommEvents,  // EV_RXCHAR、EV_CTS等
UINT writebuffersize) // size to the writebuffer
assert(portnr > 0 && portnr < 5);
assert(pPortOwner != NULL);
if (m_bThreadAlive)
{
  do
  {
    SetEvent(m_hShutdownEvent);
  }
  while (m_bThreadAlive);
  TRACE("Thread ended\n");
}
if (m_ov.hEvent != NULL)
  ResetEvent(m_ov.hEvent);
m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_hWriteEvent != NULL)
  ResetEvent(m_hWriteEvent);
m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_hShutdownEvent != NULL)
  ResetEvent(m_hShutdownEvent);
m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_hEventArray[0] = m_hShutdownEvent;
m_hEventArray[1] = m_ov.hEvent;
m_hEventArray[2] = m_hWriteEvent;
m_pOwner = pPortOwner;
if (m_szWriteBuffer != NULL)
  delete []m_szWriteBuffer;
m_szWriteBuffer = new char[writebuffersize];
m_nPortNr = portnr;
m_nWriteBufferSize = writebuffersize;
m_dwCommEvents = dwCommEvents;
EnterCriticalSection(&m_csCommunicationSync);
if (m_hComm != NULL)
{
  CloseHandle(m_hComm);
  m_hComm = NULL;
}
sprintf(szPort, "COM%d", portnr);
sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity,
  databits, stopbits);
m_hComm = CreateFile
(
  szPort,
  GENERICes_READ | GENERIC_WRITE,
  0,
  NULL,
  OPEN_EXISTING,
  FILE_FLAG_OVERLAPPED,
  0
);
m_CommTimeouts.ReadIntervalTimeout = 1000;
m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000;
m_CommTimeouts.ReadTotalTimeoutConstant = 1000;
m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
{
  if (SetCommMask(m_hComm, dwCommEvents))
  {
    if (GetCommState(m_hComm, &m_dcb))
    {
      m_dcb.fRtsControl = RTS_CONTROL_ENABLE;
      if (BuildCommDCB(szBaud, &m_dcb))
      {
        if (SetCommState(m_hComm, &m_dcb))
        else
          ProcessErrorMessage("SetCommState()");
      }
      else
        ProcessErrorMessage("BuildCommDCB()");
    }
    else
      ProcessErrorMessage("GetCommState()");
  }
  else
    ProcessErrorMessage("SetCommMask()");
  else
    ProcessErrorMessage("SetCommTimeouts()");
  delete []szPort;
  delete []szBaud PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR
    | PURGE_RXABORT | PURGE_TXABORT);
  LeaveCriticalSection(&m_csCommunicationSync);
  TRACE(
    "Initial isation for communicationport %d completed.\nUse Startmonitor to communicate. \n", portnr);
if (!(m_Thread = AfxBeginThread(CommThread, this)))
  return FALSE;
TRACE("Thread started\n");
TRACE("Thread resumed\n");
m_Thread->ResumeThread();
FormatMessage
(
  FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  NULL,
  GetLastError(),
  MAKELANGID
  (LANGesNEUTRAL, SUBLANG_DEFAULT),
  (LPTSTR) &1pMsgBuf,
  0,
  NULL
);
sprintf(Temp,
  "WARNING: %s Failed with the following error: \n%s\nPort:%d\n",
  (char*)ErrorText, 1pMsgBuf, m_nPortNr);
MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);
ResetEvent(port->m_hWriteEvent);
EnterCriticalSection(&port->m_csCommunicationSync);
if (bWrite)
{
  port->m_ov.Ofset = 0;
  port->m_ov.OffsetHigh = 0;
  PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_RXABORT |
    PURGE_TXABORT);
  bResult = WriteFile(port->m_hComm, port->m_szWriteBuffer, strlen
    ((char*)port->m_szWriteBuffer), &BytesSent, &port->m_ov);
  if (!bResult)
  {
    DWORD dwError = GetLastError();
    switch (dwError)
    {
      case ERROR_IO_PENDING:
        {
          BytesSent = 0;
          Write = FALSE;
          break;
        }
      default:
        {
          port->ProcessErrorMessage("WriteFile()");
        }
    }
  }
  else
  {
    LeaveCriticalSection(&port->m_csCommunicationSync);
  }
}

if (!bWrite)
{
  bWrite = TRUE;
  bResult = GetOverlappedResult(port->m_hComm, &port->m_ov,
    &BytesSent, TRUE);
  LeaveCriticalSection(&port->m_csCommunicationSync);
  if (!bResult)
  {
    port->ProcessErrorMessage(
      "GetOverlappedResults() in WriteFile()");
  }
}

if (BytesSent != strlen((char*)port->m_szWriteBuffer))
{
  TRACE(
    "WARNING: WriteFileQ error.. Bytes Sent: %d; Message Length: % d  \     n      ", BytesSent, strlen((char*)port->m_szWriteBuffer));
}

assert(m_hComm != 0);
memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
strcpy(m_szWriteBuffer, string);
SetEvent(m_hWriteEvent);
CCommtestDlg dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
CStartUpDlg dlg;
    m_pMainWnd=&dlg;
    int nResponse=d1gdlg.DoModal();
    if (nResponse==IDOK)
    {}
    else if (nResponse==IDCANCEL)
    {}
    return FALSE;
CStartUpDlg::CStartUpDlg(CWnd* pParent /*=NULL*/)
    :CDialog(CStartUpDlg::IDD, pParent)
{
m_hIcon=AfxGetApp()->Loadlcon(IDR_MAINFRAME);
    p_Bitmap=new CBitmap;
    p_MemoryDC=new CDC;
    b_BitmapLoaded=FALSE;
}
BOOL CStartUpdlg::OnInitDialog()
{
  CDialog::OnInitDialog();
  CPaintDC dc(this);
  p_MemoryDC->CreateCompatibleDC(&dc);
  p_Bitmap->LoadBitmap(IDB_BACKGROUND);
  BITMAP m_Bitmap;
  p_Bitmap->GetBitmap(&m_ Bitmap);
  p_Bitmap->SetBitmapDimension(m_Bitmap.bmWidth, m_Bitmap.bmHeight);
  p_MemoryDC->SelectObject(p_Bitmap);
  b_BitmapLoaded = TRUE;
  SetWindowPos(&wndTopMost,
               0,
               0,
               GetSystemMetrics(SM_CXSCREEN),
               GetSystemMetrics(SM_CYSCREEN),
               SWP_SHOWWINDOW);
  //生成两个按钮
  p_0K_Button = new CMyBtn(RGB(255, 255, 255));
  p_Exit_Button = new CMyBtn(RGB(255, 255, 255));
  CRect m_bPos;
  int height, width;
  height = GetSystemMetrics(SM_CYSCREEN) / 15;
  width = GetSystemMetrics(SM_CXSCREEN) / 8;
  height *= 2;
  width *= 2;
  //设置确定按钮的位置
  m_bPos.SetRect((GetSystemMetrics(SMes CXSCREEN) - width) / 3,
    GetSystemMetrics(SMes CYSCREEN) - height * 3 / 2,
    (GetSystemMetrics(SM_CXSCREEN) - width) / 3+width / 2,
    GetSystemMetrics(SMee CYSCREEN) - height);
  p_OK_Button->Create("确定", BS_OWNERDRAW | WS_CHILD | WS_VISIBLE
    | WS_TABSTOP, m_bPos, this, MY_OK_BUTTON);
  p_OK_Button->ShowWindow(SW_SHOW);
  //设置退出按钮的位置
  m_Pos.SetRect((GetSystemMetrics(SM_CXSCREEN) - width) *2 / 3
    +width / 2, GetSystemMetrics(SM_CYSCREEN) - height * 3 / 2,
    (GetSystemMetrics(SM_CXSCREEN) - width) *2 / 3+width,
    GetSystemMetrics(SM_CYSCREEN) - height);
  p_Exit_Button->Create("退出", BS_OWNERDRAW | WS_CHILD |
    WS_VISIBLE | WS_TABSTOP, m_bPos, this, MY_EXIT_BUTTON);
  p_Exit_Button->ShowWindow(SW_SHOW);
  return TRUE; // return TRUE unless you set the focus to a control
}
CSize m_SrcSize;
m_SrcSize = p_itmap->GetBitmapDimension();
RECT m_DestRect;
GetClientRect(&m_DestRect);
if (b_BitmapLoaded)
{
  CPaintDC dc(this);
  dc.StretchBlt
  (
    m_DestRect.left,
    m_DestRect.top,
    m_DestRect.right - m_DestRect.left,
    m_DestRect.bottom - m_DestRect.top,
    p_MemoryDC,
    0,
    0,
    m_SrcSize.cx,
    m_SrcSize.cy,
    SRCCOPY
  );
}
    void CStartUpDlg::OnOK()
    {}
    void CStartUpDlg::OnCancel()
    {}
void CStartUpDlg::OnOKButton()
{
  HWND hWnd = GetSafeHwnd();
  ShellExecute(hWnd, "open", "e:\\debug\\commtest.exe", NULL, NULL,
    SW_SHOWNORMAL);
  DestroyWindow();
}
void CStartUpDlg::OnExitButton()
{
  if (MessageBox("确定退出该应用程序吗?", "确认框",
    MB_ICONQUESTION | MB_OKCANCEL) == 2)
    return ;
  CDialog::OnCancel();
}
if (pMsg->message == WM_ KEYDOWN)
{

⌨️ 快捷键说明

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