HANDLE hThread_Read; DWORD dwThreadID; HANDLE hdev; DWORD WINAPI ThreadExecute_ReadFromEP1(PVOID pContext); hdev = INVALID_HANDLE_VALUE; hThread_Read = (HANDLE)CreateThread( NULL, 0, ThreadExecute_ReadFromEP1, this, 0, &dwThreadID); if(hThread_Read == NULL) { MessageBox("Create thread failed!"); } LRESULT CEzUSBDlgDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class if(message == WM_DEVICECHANGE) { if(wParam == DBT_DEVNODES_CHANGED) { OnCloseDevice(); } } return CDialog::WindowProc(message, wParam, lParam); } void CEzUSBDlgDlg::OnClose() { // TODO: Add your message handler code here and/or call default ::TerminateThread(hThread_Read,0); OnCloseDevice(); if(hThread_Read != NULL) { CloseHandle(hThread_Read); hThread_Read = NULL; } CDialog::OnClose(); } void CEzUSBDlgDlg::OnCloseDevice() { // TODO: Add your control notification handler code here if(hdev == INVALID_HANDLE_VALUE) { return; } CloseHandle(hdev); hdev = INVALID_HANDLE_VALUE; m_Open.EnableWindow(TRUE); m_Close.EnableWindow(FALSE); SetDlgItemText(IDC_NAME,""); } void CEzUSBDlgDlg::OnOpenDevice() { // TODO: Add your control notification handler code here if(hdev != INVALID_HANDLE_VALUE) { return; } hdev = OpenUSBDevice(); if(hdev != INVALID_HANDLE_VALUE) { m_Open.EnableWindow(FALSE); m_Close.EnableWindow(TRUE); SetDlgItemText(IDC_NAME,GetUSBDeviceName()); } else { MessageBox("Open USB device failed!"); } } void CEzUSBDlgDlg::OnRead() { // TODO: Add your control notification handler code here if(hdev == INVALID_HANDLE_VALUE) { return; } OVERLAPPED olIoControl; memset(&olIoControl, 0, sizeof(OVERLAPPED)); CHAR buff[64] = {0}; DWORD dwBytesReturned; if( (!ReadFile(hdev, buff, 64, &dwBytesReturned, &olIoControl)) && (GetLastError()!=ERROR_IO_PENDING)) { // MessageBox("ReadFile() Failed!!!"); } else { UINT m = 0; for(DWORD i=0; i<dwBytesReturned/2; i++) { m = (BYTE)buff[i*2+1]; m <<= 8; m += (BYTE)buff[i*2]; SetDlgItemInt(UID[i], m); } } } DWORD WINAPI ThreadExecute_ReadFromEP1(PVOID pContext) { CEzUSBDlgDlg* pADS = (CEzUSBDlgDlg *)pContext; while(TRUE) { pADS->OnRead(); Sleep(1); } return 0; } 一个硬件USB多线程代码实例