Waitcommevent returned error

I need to periodically read from a serial port and process the data received. Fortunately, the time between data packets, packet size and COM port settings are fixed. So I tried implementing the following read function on receipt of the EV_RXCHAR message and looped it using a SetTimer function:

I need to periodically read from a serial port and process the data received. Fortunately, the time between data packets, packet size and COM port settings are fixed. So I tried implementing the following read function on receipt of the EV_RXCHAR message
and looped it using a SetTimer function:

//Declared in the header

OVERLAPPED o;
BOOL fSuccess;
DWORD dwEvtMask;
DWORD NoBytesRead;
BYTE abBuffer[255];
CString data;


void CGCUGUIDlg::OnStartcom() 
{
     m_hComm = ::CreateFile(Com, //String that contains COM port name
            GENERIC_READ|GENERIC_WRITE,
            0,                          
            0,               
            OPEN_EXISTING,
            FILE_FLAG_OVERLAPPED,
            0
            );
          
	fnCommState();
	DCB dcb = {0};
	dcb.DCBlength = sizeof(dcb);

	Status = GetCommState(m_hComm, &dcb);
	dcb.BaudRate = CBR_115200;
	dcb.ByteSize = 8;
	dcb.StopBits = ONESTOPBIT;
	dcb.Parity = NOPARITY;
	SetCommState(m_hComm, &dcb); 

	fSuccess = SetCommMask(m_hComm,EV_RXCHAR);

	if(!fSuccess)
	{
		MessageBox("SetCommMask failed with error %s",LPCTSTR(GetLastError()));
		return;
	}
	else
		MessageBox("SetCommMask succeeded");

	memset( &o, 0, sizeof( o ) );
	o.hEvent = CreateEvent( 0, true, 0, 0 );

	SetTimer(1,20,0);	
}	


void CGCUGUIDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
    if(!WaitCommEvent(m_hComm,&dwEvtMask,&o))
		MessageBox("I/O PENDING");
	else
	{
		MessageBox("I/O RxED");
		if(dwEvtMask==EV_RXCHAR)
		{
			unsigned char ucData;
			if(!ReadFile(m_hComm,&abBuffer,sizeof(abBuffer),&NoBytesRead,&o))
			{
				MessageBox("Could not read");
			}
			if(NoBytesRead>0)
				data.Append(LPCTSTR(abBuffer),NoBytesRead);
			this->SetDlgItemText(IDC_RXRAW,LPCTSTR(data));
			this->UpdateData(FALSE);
		} //if
	} //else
	CDialog::OnTimer(nIDEvent);
}

The data is received every 50 milliseconds, so I though polling every 20 milliseconds should be safe. I am using a serial port data emulator to simulate data.

But whenever I run the code, the «I/O PENDING» message keeps popping up. I’m not sure what I am doing wrong.

Could someone point me in the right direction?


Функция WaitCommEvent ожидает какое-то
событие, которое произойдет для заданного
коммуникационного устройства. Пакет
событий, которые проверяются этой функцией,
содержится в маске события, связанной с
дескриптором устройства.

Синтаксис

BOOL WaitCommEvent(
  HANDLE hFile,
  LPDWORD lpEvtMask,
  LPOVERLAPPED lpOverlapped
);

Параметры

hFile


[in] Дескриптор коммуникационного
устройства. Функция CreateFile возвращает этот
дескриптор.

lpEvtMask


[out] Указатель на переменную,
получающую маску, указывающую тип события,
которое произошло. Если происходит ошибка,
это значение равняется нулю; в противном
случае, этот параметр — одно из ниже
перечисленного значений.

Значение Предназначение
EV_BREAK Во время ввода данных
было обнаружено прерывание.
EV_CTS Сигнал готовности к
приему (CTS) изменил состояние.
EV_DSR Сигнал готовности
модема (DSR) изменил состояние.
EV_ERR Произошла ошибка
состояния линии. Ошибкой состояния
линии являются CE_FRAME,
CE_OVERRUN и CE_RXPARITY.
EV_RING Был обнаружен
индикатор вызова.
EV_RLSD Сигнал RLSD (детектор
принимаемого линейного сигнала)
изменил состояние.
EV_RXCHAR Символ был принят и
помещен в буфер ввода данных.
EV_RXFLAG Символ события был
принят и помещен в буфер ввода данных.
Символ события определяется  в
структуре DCB устройства, которое
обращается к последовательному
порту, используя функцию SetCommState.
EV_TXEMPTY Был отправлен
последний символ из буфера вывода
данных.

lpOverlapped


[in] Указатель на структуру
OVERLAPPED. Эта структура
требуется, если hFile открывался с флажком
FILE_FLAG_OVERLAPPED.

Если hFile открывался с
FILE_FLAG_OVERLAPPED, параметр
lpOverlapped
не должен иметь значение ПУСТО (NULL).
Он должен указывать на допустимую структуру
OVERLAPPED. Если hFile открывался с FILE_FLAG_OVERLAPPED, а

lpOverlapped
— ПУСТО (NULL), функция может
неправильно сообщить, что операция
завершилась.

Если hFile открывался с
FILE_FLAG_OVERLAPPED, а lpOverlapped
— не ПУСТО (NULL), функция WaitCommEvent выполняется
как асинхронная операция. В этой ситуации, структура

OVERLAPPED
должна содержать дескриптор объекта
события сброса вручную (неавтоматического
сброса) (созданный,  при помощи
использования функции CreateEvent).

Если hFile не был открыт с
FILE_FLAG_OVERLAPPED,
WaitCommEvent
не возвращает значения до тех пор,
пока не произойдет одно из определенных
событий или ошибка.

Возвращаемые значения

Если функция завершается успешно,
возвращаемое значение не нуль.

Если функция завершается ошибкой,
возвращаемое значение равняется нулю.
Чтобы получить дополнительную информацию
об ошибке, вызовите GetLastError.

Замечания

Функция WaitCommEvent осуществляет текущий
контроль за пакетом событий для заданного
коммуникационного ресурса. Чтобы
установить и сделать запрос текущей маски
события коммуникационного ресурса,
используйте функции SetCommMask и GetCommMask.

Если асинхронная операция не может
завершиться немедленно, функцией
возвращается ЛОЖЬ (FALSE), а функцией GetLastError
возвращается значение ERROR_IO_PENDING, указывая,
что операция исполняет код в фоновом режиме.
Когда это случается, система устанавливает
член hEvent структуры OVERLAPPED в несигнальное
состояние прежде, чем WaitCommEvent возвращает
значение, а затем она устанавливает
структуру в сигнальное состояние, когда
происходит одно из определенных событий
или ошибка. Вызывающий процесс
может использовать одну из функций
ожидания
, чтобы выяснить состояние
объекта события, а затем использовать
функцию GetOverlappedResult, чтобы выяснить
результат работы  WaitCommEvent. Функция
GetOverlappedResult
сообщает об успешном завершении
или сбое операции, а переменная, на которую
указывает параметр lpEvtMask устанавливается
так, чтобы обозначить событие, которое
произошло.

Если процесс пытается изменить маску
события дескриптора устройства, используя
функцию SetCommMask, в то время, когда происходит
асинхронная операция WaitCommEvent, функция
WaitCommEvent
возвращает значение немедленно.
Переменная, на которую указывает параметр
lpEvtMask
устанавливается в нуль (‘0’).

Код примера

Пример смотри в статье
Мониторинг
коммуникационных событий
.

Смотри также

Обзор Коммуникационные
ресурсы, Функции,
используемые коммуникационными ресурсами,
CreateFile
,
DCB
, GetCommMask,

GetOverlappedResult,
OVERLAPPED, SetCommMask,
SetCommState




















Размещение и
совместимость
WaitCommEvent

К

Windows XP

Да



л

Windows 2000
Professional

Да



и

Windows NT 
Workstation

Да



е

Windows Me

Да



н

Windows 98

Да

т


Windows 95

Да


 

С

Windows 2003 Server

Да

е

Windows 2000 Server

Да 

р

Windows NT Server

Да

в

 

е

 
р 

 
 

Используемая
библиотека

Kernel32.lib


 

Заголовочный файл

 
 

— объявлено в

Winbase.h


 

— включено в

Windows.h


 

Unicode


 

Замечания по
платформе

Не имеется

Hosted by uCoz

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • WaitCommEvent Failing

  1. Feb 15th, 2013, 05:43 PM


    #1

    Ken Whiteman is offline

    Thread Starter


    Hyperactive Member


    WaitCommEvent Failing

    Hi everyone,

    Here is a code snippet I’m having trouble with:

    Code:

        Select Case WaitCommEvent(hPort, commEvtMask, ComEvent)
            Case 0          'Error
                dwRet = Err.LastDllError
                dwRetStr = Err.Description
                Select Case dwRet
                    Case ERROR_IO_PENDING
                        OpenPortTxt = "I/O is pending..."
                    Case Else
                        OpenPortTxt = "Port " & PName & "Wait failed with error " & dwRet & " >> " & dwRetStr
                End Select
            Case Else       'Successful
                If (dwEvtMask Or EV_CTS Or EV_DSR) Then
                    Form1.Text4.Text = serapi.RXport
                    OpenPortTxt = "It worked!"
                End If
        End Select

    When this function executes, it returns ERROR_IO_PENDING
    I’m not sure how to fix this or even troublshoot it!
    Can someone help please?

    Thanks,
    Ken


  2. Feb 15th, 2013, 06:38 PM


    #2

    Re: WaitCommEvent Failing

    Is that the whole function? How are the variables declared?

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  3. Feb 15th, 2013, 06:44 PM


    #3

    Re: WaitCommEvent Failing

    From the Remarks section of the WaitCommEvent function:

    Quote Originally Posted by MSDN

    If the overlapped operation cannot be completed immediately, the function returns FALSE (0) and the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing in the background.

    Is your ComEvent variable declared as an OVERLAPPED type?

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  4. Feb 18th, 2013, 10:26 AM


    #4

    Ken Whiteman is offline

    Thread Starter


    Hyperactive Member


    Re: WaitCommEvent Failing

    Thanks Bonnie!

    Here’s the entire function and declares:

    Code:

     
    Function OpenPort(PName As String, PSettings As String) As String
    'This function returns a null string "" if it succeeds,
    'otherwise it returns an error which can be MsgBoxed or
    'ignored as appropriate
    
    Dim CMask As Long
    Dim WCom As Long
    Dim RVal1 As String
    Dim RVal As Long
    Dim PortStr As String
    Dim PSA As SECURITY_ATTRIBUTES
    Dim Timeouts As COMMTIMEOUTS
    Dim ADCB As DCB
    Dim aa As String
    Dim bb As Long
    Dim commEvtMask As Long
    Dim commEvtMaskGet As Long
    Dim ComEvent As OVERLAPPED
    Dim dwRet As Long
    Dim dwRetStr As String
    
        aa = Trim("\." & PName)
        
        hPort = CreateFile( _
            aa, _
            FILE_GENERIC_WRITE Or FILE_GENERIC_READ, _
            0, _
            PSA, _
            OPEN_EXISTING, _
            FILE_FLAG_OVERLAPPED, _
            0)
            
        If hPort = INVALID_HANDLE_VALUE Then
            RVal1 = Err.Description
            RVal = GetLastError
            OpenPort = "Can't Open Port " + PName + "."
            Exit Function
        End If
        '
        portHandle = hPort
        '
        'Now we set the timeouts so that ReadFile() will return
        'immediately instead of blocking if there is no data.
        '
        Timeouts.ReadIntervalTimeout = MAXDWORD
        Timeouts.ReadTotalTimeoutMultiplier = 0
        Timeouts.ReadTotalTimeoutConstant = 0
        Timeouts.WriteTotalTimeoutMultiplier = 0
        Timeouts.WriteTotalTimeoutConstant = 0
        RVal = SetCommTimeouts(hPort, Timeouts)
        If RVal = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Couldn't set port " + PName + " timeouts."
            Exit Function
        End If
        '
        RVal = BuildCommDCB(PSettings, ADCB)
        If RVal = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Port " & PName & " DCB Build failed: " & PSettings
            Exit Function
        End If
        '
        RVal = SetCommState(hPort, ADCB)
        If RVal = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Port " & PName & " SetCommState failed: " & PSettings
            Exit Function
        End If
        '
        commEvtMask = EV_TXEMPTY Or EV_RXCHAR
        RVal = SetCommMask(hPort, commEvtMask)
        If RVal = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Port " & PName & " SetCommMask failed: " & GetLastError()
            Exit Function
        End If
        '
        bb = GetCommMask(hPort, commEvtMaskGet)
        If bb = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Port " & PName & " GetCommMask failed: " & GetLastError()
            Exit Function
        End If
        '
        ComEvent.hEvent = CreateEvent(PSA, False, False, "OnComm")
        If ComEvent.hEvent = 0 Then
            Call CloseHandle(hPort)
            OpenPort = "Port " & PName & " OnComm Event not created: " & GetLastError()
            Exit Function
        End If
        
        Select Case WaitCommEvent(hPort, commEvtMask, ComEvent)
            Case 0          'Error
                dwRet = Err.LastDllError
                dwRetStr = Err.Description
                Select Case dwRet
                    Case ERROR_IO_PENDING
                        OpenPort = "I/O is pending..."
                    Case Else
                        OpenPort = "Port " & PName & "Wait failed with error " & dwRet & " >> " & dwRetStr
                End Select
            Case Else       'Successful
                If (dwEvtMask Or EV_CTS Or EV_DSR) Then
                    Form1.Text4.Text = serapi.RXport
                    OpenPort = "It worked!"
                End If
        End Select
        
    End Function

    Declares:

    Code:

    Public portHandle As Long
    
    Public hPort As Long
    Public olWritePort As OVERLAPPED
    Public olWritePending As Boolean
    Public olWriteBuffer As String
    Public olReadPort As OVERLAPPED
    Public olCommEvent As OVERLAPPED
    
    Public Const FILE_GENERIC_READ = _
        (STANDARD_RIGHTS_READ Or FILE_READ_DATA Or FILE_READ_ATTRIBUTES Or _
        FILE_READ_EA Or SYNCHRONIZE)
    '
    Public Const FILE_GENERIC_WRITE = _
        (STANDARD_RIGHTS_WRITE Or FILE_WRITE_DATA Or FILE_WRITE_ATTRIBUTES Or _
        FILE_WRITE_EA Or FILE_APPEND_DATA Or SYNCHRONIZE)
    
    Type SECURITY_ATTRIBUTES
            nLength As Long
            lpSecurityDescriptor As Long
            bInheritHandle As Long
    End Type
    
    Type OVERLAPPED
            Internal As Long
            InternalHigh As Long
            offset As Long
            OffsetHigh As Long
            hEvent As Long
    End Type
    
    Type DCB
            DCBlength As Long
            BaudRate As Long
            fBitFields As Long
            wReserved As Integer
            XonLim As Integer
            XoffLim As Integer
            ByteSize As Byte
            Parity As Byte
            StopBits As Byte
            XonChar As Byte
            XoffChar As Byte
            ErrorChar As Byte
            EofChar As Byte
            EvtChar As Byte
            wReserved1 As Integer
    End Type
    
    Declare Function BuildCommDCB Lib "kernel32" Alias "BuildCommDCBA" _
        (ByVal lpDef As String, lpDCB As DCB) As Long
    '
    Declare Function SetCommState Lib "kernel32" _
        (ByVal hCommDev As Long, lpDCB As DCB) As Long
    '
    Declare Function GetCommState Lib "kernel32" _
        (ByVal hFile As Long, lpDCB As DCB) As Long
    '
    Declare Function SetCommTimeouts Lib "kernel32" _
        (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As Long
    '
    Declare Function ClearCommError Lib "kernel32" _
        (ByVal hFile As Long, lpErrors As Long, lpStat As COMSTAT) As Long
    '
    Declare Function GetLastError Lib "kernel32" () As Long
    '
    Declare Function GetOverlappedResult Lib "kernel32" _
        (ByVal hFile As Long, lpOverlapped As OVERLAPPED, _
        lpNumberOfBytesTransferred As Long, ByVal bWait As Long) As Long
    '
    Declare Function PurgeComm Lib "kernel32" _
        (ByVal hFile As Long, ByVal dwFlags As Long) As Long
    
    Declare Function GetCommModemStatus Lib "kernel32" _
        (ByVal hFile As Long, lpModemStat As Long) As Long
    '
    Public Enum EVTMASK
        EV_CTS = &H8 ' CTS changed state
        EV_DSR = &H10 ' DSR changed state
        EV_ERR = &H80 ' Line status error occurred
        EV_EVENT1 = &H800 ' Provider specific event 1
        EV_EVENT2 = &H1000 ' Provider specific event 2
        EV_PERR = &H200 ' Printer error occured
        EV_RING = &H100 ' Ring signal detected
        EV_RLSD = &H20 ' RLSD changed state
        EV_RX80FULL = &H400 ' Receive buffer is 80 percent full
        EV_RXCHAR = &H1 ' Any Character received
        EV_RXFLAG = &H2 ' Received certain character
        EV_TXEMPTY = &H4 ' Transmitt Queue Empty
        EV_BREAK = &H40 ' BREAK received
    End Enum
    Declare Function SetCommMask Lib "kernel32" (ByVal hFile As Long, ByVal dwEvtMask As EVTMASK) As Long
    '
    Declare Function GetCommMask Lib "kernel32" (ByVal hFile As Long, ByVal dwEvtMask As EVTMASK) As Long
    '
    Declare Function WaitCommEvent Lib "kernel32" _
        (ByVal hFile As Long, _
        dwEvtMask As EVTMASK, _
        lpOverlapped As OVERLAPPED) As Long

    I’m hoping this is something easy for you to spot!


  5. Feb 18th, 2013, 10:57 AM


    #5

    Re: WaitCommEvent Failing

    Quote Originally Posted by Ken Whiteman
    View Post

    Here’s the entire function and declares:

    VB keeps finding undefined identifiers every time it tries to run; currently supplying the missing APIs myself…

    EDIT1

    Are you using Option Explicit? The dwEvtMask variable in the line

    If (dwEvtMask Or EV_CTS Or EV_DSR) Then was undeclared. It probably should have been commEvtMask instead…

    EDIT2

    From GetLastError function:

    Quote Originally Posted by MSDN

    Visual Basic: Applications should call Err.LastDllError instead of GetLastError.

    EDIT3

    Ampersand (&) is more preferred than Addition (+) when concatenating strings.

    EDIT4

    It appears

    ADCB.DCBlength wasn’t initialized to LenB(ADCB).

    Quote Originally Posted by MSDN

    DCBlength

    The length of the structure, in bytes. The caller must set this member to sizeof(DCB).

    EDIT5

    GetCommMask’s dwEvtMask parameter should be ByRef. Also, GetCommMask is typically called before SetCommMask, unless there’s a valid reason for doing otherwise.

    EDIT6

    Err.Description isn’t meant to return an error description from a failed API call. Use this instead:

    Code:

    Private Declare Function FormatMessage Lib "kernel32.dll" Alias "FormatMessageW" (ByVal dwFlags As Long, ByVal lpSource As Long, ByVal dwMessageId As Long, ByVal dwLanguageId As Long, ByVal lpBuffer As Long, ByVal nSize As Long, Optional ByVal Arguments As Long) As Long
    
    Public Function GetErrMsg(ByVal LastDllError As Long) As String
        Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000&, MAX_BUFFER = &H10000
    
        GetErrMsg = Space$(MAX_BUFFER - 1&)
        GetErrMsg = Left$(GetErrMsg, FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0&, LastDllError, 0&, StrPtr(GetErrMsg), MAX_BUFFER))
    End Function

    EDIT7

    I assume the public variables hPort and portHandle are CloseHandle’d elsewhere. If there are still errors after applying the above fixes, I would advice you to carefully read the documentation for each API again.

    Last edited by Bonnie West; Feb 18th, 2013 at 12:54 PM.

    Reason: Found another bug

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  6. Feb 20th, 2013, 11:15 AM


    #6

    Ken Whiteman is offline

    Thread Starter


    Hyperactive Member


    Re: WaitCommEvent Failing

    Hi Bonnie!

    Thanks for taking the time to help me with this.

    I have implemented all the edits you suggested, but I’m still getting «error 997 Overlapped I/O operation is in progress».

    I’ve uploaded my project, and am asking if you could take a look and see what’s wrong.

    Please understand, this is a small test project I created to work out the details of serial comm.
    Once this is working correctly, I will replace the MSComm OCX’s in my real project with the this new code.

    Thanks again!

    Ken


  7. Feb 20th, 2013, 11:24 AM


    #7

    Ken Whiteman is offline

    Thread Starter


    Hyperactive Member


    Re: WaitCommEvent Failing

    Notes on the Zipped file:

    When the code is first executed, it checks for the existence of com1 to com16, followed by a beep indicating port checking is complete.
    When the «Close Port» button is pressed, it will again check for comm ports.

    Sometimes after an error, and «Close Port» is pressed the comm port is no longer available.
    The only way I have found to restore availability without rebooting, is to close VB6, open Hyperterm.
    Connect to the com port (open) then immediately close and exit Hyperterm.
    Then re-load VB6 and project.
    Don’t know what�s getting hung up in the comm routines, that won’t get released.
    Any ideas?

    Ken


  8. Feb 20th, 2013, 11:44 AM


    #8

    Re: WaitCommEvent Failing

    Quote Originally Posted by Ken Whiteman
    View Post

    … I will replace the MSComm OCX’s in my real project with the this new code.

    Why, what’s wrong with it?

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  9. Feb 20th, 2013, 01:39 PM


    #9

    Re: WaitCommEvent Failing

    Quote Originally Posted by Ken Whiteman
    View Post

    … but I’m still getting «error 997 Overlapped I/O operation is in progress».

    I’m getting that same error as well. I think that’s to be expected since you’ve specified in the CreateFile line the FILE_FLAG_OVERLAPPED flag, which causes WaitCommEvent to be performed as an overlapped (asynchronous) operation. That means, WaitCommEvent won’t actually wait. See the Remarks on WaitCommEvent’s documentation. In order to really wait, the manual recommends using one of the wait functions. The Communications Events topic may shed some light on your issue.

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  10. Feb 22nd, 2013, 01:00 PM


    #10

    Ken Whiteman is offline

    Thread Starter


    Hyperactive Member


    Re: WaitCommEvent Failing

    I’ve spent the last 2 days trying to get this right. Not having much luck.

    Bonnie:

    In the last post, you made mention that «the WaitCommEvent won’t actually wait».
    I’m not certain I want it to wait. I really need my program to not stop other functions/processes while waiting for a character to appear in the buffer.
    In fact, I want to tell the system to quietly monitor the port for activity, and alert me only when a signal appears, otherwise, just continue to do other things as normal.
    Basically, opperate as an interupt!

    Can you re-direct me in the right direction?

    Thanks,
    Ken


  11. Feb 22nd, 2013, 01:45 PM


    #11

    Re: WaitCommEvent Failing

    Quote Originally Posted by Ken Whiteman
    View Post

    Can you re-direct me in the right direction?

    I was already trying to do that in posts #3 and #9. Like I said, you’ll have to use one of the wait functions in order to be notified when an event occurs (while doing other tasks in the meantime). Have you read the Remarks section of WaitCommEvent’s doc? Have you also taken a look at the Communications Events topic? It explains there everything you need to know about using WaitCommEvent asynchronously (overlapped).

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • WaitCommEvent Failing


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Waitauthplayerloginstate dayz ошибка
  • Wait input time out ошибка researchdownload
  • Wait for sync mutex error перевод
  • Wait for f1 key to be pressed if error occurs
  • Wait for decrypt oem code error 50502 unsupported modem fw