comevent.c

来自「USB转串口的虚拟串口驱动 USB2COM 是给USB转串口转换器写的虚拟串」· C语言 代码 · 共 92 行

C
92
字号
#include <windows.h>
#include <stdio.h>
#include <assert.h>

int _cdecl main(int argc, char *argv[])
{	
	HANDLE hCom;
	OVERLAPPED o;
	BOOL fSuccess;
	DWORD dwEvtMask;
	
	hCom = CreateFile( "COM9",
	    GENERIC_READ | GENERIC_WRITE,
	    0,    // exclusive access 
	    NULL, // no security attributes 
	    OPEN_EXISTING,
	    FILE_FLAG_OVERLAPPED,
	    NULL
	    );
	
	if (hCom == INVALID_HANDLE_VALUE) 
	{
	    // Handle the error. 
	}
	
	// Set the event mask. 
	
	fSuccess = SetCommMask(hCom, EV_RXCHAR|EV_TXEMPTY );
	
	if (!fSuccess) 
	{
	    // Handle the error. 
	}
	
	// Create an event object for use in WaitCommEvent. 
	
	o.hEvent = CreateEvent(
	    NULL,   // no security attributes 
	    FALSE,  // auto reset event 
	    FALSE,  // not signaled 
	    NULL    // no name 
	    );
	
	assert(o.hEvent);
	
	if (WaitCommEvent(hCom, &dwEvtMask, &o)) 
	{
	    if (dwEvtMask & EV_RXCHAR) 
	    {
	         // To do.
	    }
	
	    if (dwEvtMask & EV_TXEMPTY) 
	    {
	         // To do. 
	    }
	}else
    {
        DWORD dwRet = GetLastError();
        if( ERROR_IO_PENDING == dwRet)
        {
            printf("I/O is pending...\n");
			dwRet = WaitForSingleObject(
						o.hEvent,        // handle to object
						INFINITE   // time-out interval
						);

			switch (dwRet)
			{
				case WAIT_ABANDONED:
					printf("WAIT_ABANDONED\n");
					break;
				case WAIT_TIMEOUT:
					printf("WAIT_TIMEOUT\n");
					break;
				case WAIT_OBJECT_0:
				{
					printf("WAIT_OBJECT_0 %x\n",dwEvtMask);
					break;
				}
				default:
					break;
			}
            // To do.
        }
        else 
            printf("Wait failed with error %d.\n", GetLastError());
    }
	CloseHandle(hCom);

	return 0;
}

⌨️ 快捷键说明

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