void CSerialPort::ClosePort()
{
if (m_bThreadAlive)
{
do
{
SetEvent(m_hShutdownEvent);
} while (m_bThreadAlive);
TRACE("Thread ended\n");
}
if (m_hComm != NULL)
{
CloseHandle(m_hComm);
m_hComm = NULL;
}
}
//在VIEW中调用m_CommPort.ClosePort();在没通信时可正常关闭,有通信时程序有时会死了

解决方案 »

  1.   

    #include "stdafx.h"
    #include "SerialPort.h"#include <assert.h> 
    //
    // Constructor
    //
    CSerialPort::CSerialPort()
    {
    m_hComm = NULL; // initialize overlapped structure members to zero
    m_ov.Offset = 0;
    m_ov.OffsetHigh = 0; // create events
    m_ov.hEvent = NULL;
    m_hWriteEvent = NULL;
    m_hShutdownEvent = NULL; m_szWriteBuffer = NULL;
    m_nWriteSize=1; m_bThreadAlive = FALSE;
    }//
    // Delete dynamic memory
    //
    CSerialPort::~CSerialPort()
    {
    do
    {
    SetEvent(m_hShutdownEvent);
    } while (m_bThreadAlive);
    TRACE("Thread ended\n");
    delete [] m_szWriteBuffer;
    }//
    // Initialize the port. This can be port 1 to 4.
    //
    BOOL CSerialPort::InitPort(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message)
       UINT  portnr, // portnumber (1..4)
       UINT  baud, // baudrate
       char  parity, // parity 
       UINT  databits, // databits 
       UINT  stopbits, // stopbits 
       DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc
       UINT  writebuffersize) // size to the writebuffer
    {
    assert(portnr > 0 && portnr < 5);
    assert(pPortOwner != NULL);
    // if the thread is alive: Kill
    if (m_bThreadAlive)
    {
    do
    {
    SetEvent(m_hShutdownEvent);
    } while (m_bThreadAlive);
    TRACE("Thread ended\n");
    } // create events
    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); // initialize the event objects
    m_hEventArray[0] = m_hShutdownEvent; // highest priority
    m_hEventArray[1] = m_ov.hEvent;
    m_hEventArray[2] = m_hWriteEvent; // initialize critical section
    InitializeCriticalSection(&m_csCommunicationSync);

    // set buffersize for writing and save the owner
    m_pOwner = pPortOwner; if (m_szWriteBuffer != NULL)
    delete [] m_szWriteBuffer;
    m_szWriteBuffer=new unsigned char[writebuffersize]; m_nPortNr = portnr; m_nWriteBufferSize = writebuffersize;
    m_dwCommEvents = dwCommEvents; BOOL bResult = FALSE;
    char *szPort = new char[50];
    char *szBaud = new char[50]; // now it critical!
    EnterCriticalSection(&m_csCommunicationSync); // if the port is already opened: close it
    if (m_hComm != NULL)
    {
    CloseHandle(m_hComm);
    m_hComm = NULL;
    } // prepare port strings
    sprintf(szPort, "COM%d", portnr);
    sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopbits); // get a handle to the port
    m_hComm = CreateFile(szPort, // communication port string (COMX)
         GENERIC_READ | GENERIC_WRITE, // read/write types
         0, // comm devices must be opened with exclusive access
         NULL, // no security attributes
         OPEN_EXISTING, // comm devices must use OPEN_EXISTING
         FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, // Async I/O
         0); // template must be 0 for comm devices if (m_hComm == INVALID_HANDLE_VALUE)
    {
    // port not found
    delete [] szPort;
    delete [] szBaud; return FALSE;
    } // set the timeout values
    m_CommTimeouts.ReadIntervalTimeout = 1000;
    m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000;
    m_CommTimeouts.ReadTotalTimeoutConstant = 1000;
    m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
    m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
    // configure
    if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
    {    
    if (SetCommMask(m_hComm, dwCommEvents))
    {
    if (GetCommState(m_hComm, &m_dcb))
    {
    m_dcb.EvtChar = 'q';
    m_dcb.fRtsControl=RTS_CONTROL_TOGGLE;//RTS_CONTROL_DISABLE;//RTS_CONTROL_ENABLE;//   set RTS bit high!
    if (BuildCommDCB(szBaud, &m_dcb))
    {
    if (SetCommState(m_hComm, &m_dcb))
    ; // normal operation... continue
    else
    ProcessErrorMessage("SetCommState()");
    }
    else
    ProcessErrorMessage("BuildCommDCB()");
    }
    else
    ProcessErrorMessage("GetCommState()");
    }
    else
    ProcessErrorMessage("SetCommMask()");
    }
    else
    ProcessErrorMessage("SetCommTimeouts()"); delete [] szPort;
    delete [] szBaud; // flush the port
    PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); // release critical section
    LeaveCriticalSection(&m_csCommunicationSync); TRACE("Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n", portnr); return TRUE;
    }//
    //  The CommThread Function.
    //
    UINT CSerialPort::CommThread(LPVOID pParam)
    {
    CSerialPort *port = (CSerialPort*)pParam;
    port->m_bThreadAlive = TRUE; DWORD BytesTransfered = 0; 
    DWORD Event = 0;
    DWORD CommEvent = 0;
    DWORD dwError = 0;
    COMSTAT comstat;
    BOOL  bResult = TRUE;

    if (port->m_hComm) //初始化,清除发送接收缓冲区,清除发送、接收的重叠I/O操作
    PurgeComm(port->m_hComm,PURGE_RXCLEAR|PURGE_TXCLEAR|PURGE_RXABORT|PURGE_TXABORT);
    //开始 循环等待操作
    for (;;) 

    bResult=WaitCommEvent(port->m_hComm, &Event, &port->m_ov);
    //无限等待设定的事件发生,数组Event根据需要定义了须响应的接收,发送,关闭端口事件和OVERLAPPED类型的hEvent事件
    if (!bResult)  

    switch (dwError = GetLastError()) 

    case ERROR_IO_PENDING:  //I/O操作还没有完成,函数返回0

    break;
    }
    case 87: //NT WILL RETURN
    {
    break;
    }
    default:
    {
    port->ProcessErrorMessage("WaitCommEvent()");
    break;
    }
    }
    }
    else
    {
    bResult = ClearCommError(port->m_hComm, &dwError, &comstat);//清除通信发生的错误
    if (comstat.cbInQue==0)
    continue;
    } // end if bResult
    Event = WaitForMultipleObjects(3, port->m_hEventArray, FALSE, INFINITE);
    switch (Event)
    {
    case 0:
    {
    CloseHandle(port->m_hComm);
    port->m_hComm=NULL;
    port->m_bThreadAlive = FALSE;
    AfxEndThread(100);
    break;
    }
    case 1: // read event
    {
    GetCommMask(port->m_hComm, &CommEvent);
    if (CommEvent & EV_RXCHAR) //接受到一个字符并放入输入缓冲区
    ReceiveChar(port, comstat);
    if (CommEvent & EV_CTS) //CTS(清除发送)改变状态
    ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_CTS_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    if (CommEvent & EV_BREAK) //检测到输入的终止
    ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_BREAK_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    if (CommEvent & EV_ERR) //发生了线路状态错误
    ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_ERR_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    if (CommEvent & EV_RING) //检测到振铃
    ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RING_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    if (CommEvent & EV_RXFLAG) //接收到事件字符(DCB结构的EvtChar成员),并放入输入缓冲区
    ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RXFLAG_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    break;
    }  
    case 2: // write event
    {
    //              EscapeCommFunction(port->m_hComm,SETRTS);
    WriteChar(port);
    // GetCommMask(port->m_hComm, &CommEvent);
    // if(CommEvent==EV_TXEMPTY)
    // {
    // EscapeCommFunction(port->m_hComm,CLRRTS);
    // ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_TXEMPTY_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
    // }
    break;
    }
    } // end switch
    } // close forever loop
    return 0;
    }
      

  2.   

    // start comm watching
    BOOL CSerialPort::StartMonitoring()
    {
    if (!(m_Thread = AfxBeginThread(CommThread, this)))
    return FALSE;
    TRACE("Thread started\n");
    return TRUE;
    }
    //
    // Restart the comm thread
    BOOL CSerialPort::RestartMonitoring()
    {
    TRACE("Thread resumed\n");
    m_Thread->ResumeThread();
    return TRUE;
    }
    //
    // Suspend the comm thread
    BOOL CSerialPort::StopMonitoring()
    {
    TRACE("Thread suspended\n");
    m_Thread->SuspendThread(); 
    return TRUE;
    }
    //
    // If there is a error, give the right message
    void CSerialPort::ProcessErrorMessage(char* ErrorText)
    {
    char *Temp = new char[200];

    LPVOID lpMsgBuf; FormatMessage( 
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL 
    );
    sprintf(Temp, "WARNING:  %s Failed with the following error: \n%s\nPort: COM%d\n", (char*)ErrorText, lpMsgBuf, m_nPortNr); 
    MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);
    LocalFree(lpMsgBuf);
    delete [] Temp;
    }
    //
    // Write a character.
    void CSerialPort::WriteChar(CSerialPort* port)
    {
    BOOL bWrite = TRUE;
    BOOL bResult = TRUE;
    DWORD BytesSent = 0;
    ResetEvent(port->m_hWriteEvent);
    // Gain ownership of the critical section
    EnterCriticalSection(&port->m_csCommunicationSync); if (bWrite)
    {
    port->m_ov.Offset = 0;
    port->m_ov.OffsetHigh = 0;
    // Clear buffer
    PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
    bResult = WriteFile(port->m_hComm, // Handle to COMM Port
    port->m_szWriteBuffer, // Pointer to message buffer in calling finction
    port->m_nWriteSize, // Length of message to send
    &BytesSent, // Where to store the number of bytes sent
    &port->m_ov); // Overlapped structure
    // deal with any error codes
    if (!bResult)  
    {
    DWORD dwError = GetLastError();
    switch (dwError)
    {
    case ERROR_IO_PENDING:
    {
    // continue to GetOverlappedResults()
    BytesSent = 0;
    bWrite = FALSE;
    break;
    }
    default:
    port->ProcessErrorMessage("WriteFile()");// all other error codes
    }

    else
    LeaveCriticalSection(&port->m_csCommunicationSync);
    }
    if (!bWrite)
    {
    bWrite = TRUE;
    bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port 
      &port->m_ov, // Overlapped structure
      &BytesSent, // Stores number of bytes sent
      TRUE);  // Wait flag
    LeaveCriticalSection(&port->m_csCommunicationSync);
    }
    ::SendMessage((port->m_pOwner)->m_hWnd, WM_COMM_TXEMPTY_DETECTED,0,(LPARAM) port->m_nPortNr);
    }void CSerialPort::ReceiveChar(CSerialPort* port, COMSTAT comstat)
    {
    BOOL  bRead = TRUE; 
    BOOL  bResult = TRUE;
    DWORD dwError = 0;
    DWORD BytesRead = 0;
    unsigned char RXBuff;
    for (;;) 

    // Gain ownership of the comm port critical section.
    // This process guarantees no other part of this program 
    // is using the port object. 
    EnterCriticalSection(&port->m_csCommunicationSync);
    // ClearCommError() will update the COMSTAT structure and
    // clear any other errors.
    bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
    LeaveCriticalSection(&port->m_csCommunicationSync);
    // start forever loop.  I use this type of loop because I
    // do not know at runtime how many loops this will have to
    // run. My solution is to start a forever loop and to
    // break out of it when I have processed all of the
    // data available.  Be careful with this approach and
    // be sure your loop will exit.
    // My reasons for this are not as clear in this sample 
    // as it is in my production code, but I have found this 
    // solutiion to be the most efficient way to do this.

    if (comstat.cbInQue == 0)
    {
    // break out when all bytes have been read
    break;
    }

    EnterCriticalSection(&port->m_csCommunicationSync); if (bRead)
    {
    bResult = ReadFile(port->m_hComm, // Handle to COMM port 
       &RXBuff, // RX Buffer Pointer
       1, // Read one byte
       &BytesRead, // Stores number of bytes read
       &port->m_ov); // pointer to the m_ov structure
    // deal with the error code 
    if (!bResult)  

    switch (dwError = GetLastError()) 

    case ERROR_IO_PENDING: 

    // asynchronous i/o is still in progress 
    // Proceed on to GetOverlappedResults();
    bRead = FALSE;
    break;
    }
    default:
    {
    // Another error has occured.  Process this error.
    port->ProcessErrorMessage("ReadFile()");
    break;

    }
    }
    else
    {
    // ReadFile() returned complete. It is not necessary to call GetOverlappedResults()
    bRead = TRUE;
    }
    }  // close if (bRead) if (!bRead)
    {
    bRead = TRUE;
    bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port 
      &port->m_ov, // Overlapped structure
      &BytesRead, // Stores number of bytes read
      TRUE);  // Wait flag // deal with the error code 
    if (!bResult)  
    {
    port->ProcessErrorMessage("GetOverlappedResults() in ReadFile()");
    }
    }  // close if (!bRead)

    LeaveCriticalSection(&port->m_csCommunicationSync); // notify parent that a byte was received
    ::SendMessage((port->m_pOwner)->m_hWnd, WM_COMM_RXCHAR, (WPARAM) RXBuff, (LPARAM) port->m_nPortNr);
    } // end forever loop}
    void CSerialPort::WriteToPort(unsigned char* string,int n)
    {
    assert(m_hComm != 0);
    memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
    memcpy(m_szWriteBuffer,string,n);
    m_nWriteSize=n;
    SetEvent(m_hWriteEvent);
    }void CSerialPort::WriteToPort(LPCTSTR string,int n)
    {
    assert(m_hComm != 0); memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
    memcpy(m_szWriteBuffer,string,n);
    m_nWriteSize=n;
    SetEvent(m_hWriteEvent);
    }
    DCB CSerialPort::GetDCB()
    {
    return m_dcb;
    }
    DWORD CSerialPort::GetCommEvents()
    {
    return m_dwCommEvents;
    }
    DWORD CSerialPort::GetWriteBufferSize()
    {
    return m_nWriteBufferSize;
    }
    void CSerialPort::ClosePort()
    {
    if (m_bThreadAlive)
    {
    do
    {
    SetEvent(m_hShutdownEvent);
    } while (m_bThreadAlive);
    TRACE("Thread ended\n");
    }
    if (m_hComm != NULL)
    {
    CloseHandle(m_hComm);
    m_hComm = NULL;
    }
    }
      

  3.   

    加一句
    if (m_bThreadAlive)
    {
    do
    {
    SetCommMask(m_hComm, NULL);//还不行就换SetEvent( m_ov.hEvent);
    SetEvent(m_hShutdownEvent);
    } while (m_bThreadAlive);
    TRACE("Thread ended\n");
    }