检测USB插入拔出

heton 2002-09-02 01:47:56
我写了段代码:

// CheckUsb.cpp : Defines the entry point for the application.
//

#include "stdafx.h"

HWND hwndMain;

LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{

switch(uMsg)
{
case WM_CREATE:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
break;
case WM_DEVICECHANGE:
MessageBox(NULL,"设备改变","提示",MB_OK);
break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.

WNDCLASSEX wclass;
MSG msg;

wclass.cbClsExtra = 0;
wclass.cbSize = sizeof(WNDCLASSEX);
wclass.cbWndExtra = 0;
wclass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH);
wclass.hCursor = NULL;
wclass.hIcon = NULL;
wclass.hIconSm = NULL;
wclass.hInstance = hInstance;
wclass.lpfnWndProc =(WNDPROC)WndProc;
wclass.lpszClassName = "CheckUSB";
wclass.lpszMenuName = NULL;
wclass.style = CS_DBLCLKS;



if(!RegisterClassEx(&wclass))
{
MessageBox(NULL,"类创建失败","类创建失败",MB_OK);
}
hwndMain = CreateWindow("CheckUSB","检测USB设备",
WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 320, 300,NULL, NULL, hInstance, NULL);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg); //translate the message into its char equivelent
DispatchMessage(&msg);
}

return msg.wParam;
}



如何在WM_DEVICECHANGE消息处判断是不是USB插入或者拔出
...全文
1148 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
afc 2002-10-05
  • 打赏
  • 举报
回复
Recognizing Device Changes [Language: C++]
[Visual Basic]
This topic pertains only to applications written in C++.
[C++]
Because universal serial bus (USB) devices can be added to and removed from the system without rebooting, you might want your application to be able to respond to a new configuration of input devices. For example, you might allow a new player to join a game in progress by plugging in another controller.

To receive a message when a device is changed, you must first register for notification, as in the following code example:

PVOID hNotifyDevNode;

void RegisterForDevChange(HWND hDlg, PVOID *hNotifyDevNode)
{
DEV_BROADCAST_DEVICEINTERFACE *pFilterData =
(DEV_BROADCAST_DEVICEINTERFACE*)
_alloca(sizeof(DEV_BROADCAST_DEVICEINTERFACE));
ASSERT (pFilterData);

ZeroMemory(pFilterData, sizeof(DEV_BROADCAST_DEVICEINTERFACE));

pFilterData->dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
pFilterData->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
pFilterData->dbcc_classguid = GUID_CLASS_INPUT;

*hNotifyDevNode = RegisterDeviceNotification(hDlg, pFilterData,
DEVICE_NOTIFY_WINDOW_HANDLE);
}
Then, in your main window procedure, check for messages announcing that a device has been attached, is about to be removed, or has been removed, as follows:

MyWindowProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
switch (nMsg)
{
case WM_DEVICECHANGE:
{
switch (wParam)
{
case DBT_DEVICEARRIVAL:
// Handle device arrival
break;

case DBT_DEVICEQUERYREMOVE:
// Handle device removal request
break;

case DBT_DEVICEREMOVECOMPLETE:
// Handle device removal
break;
}
}
.
.
.
}
}
afc 2002-10-05
  • 打赏
  • 举报
回复
创建窗口之后用RegisterDeviceNotification注册设备通知才可以收到更多的设备通知信息
yaotang 2002-10-05
  • 打赏
  • 举报
回复
Study
heton 2002-09-05
  • 打赏
  • 举报
回复
在WIN2000 的设备管理里面(通用串行总线控制器),我可以看到我的USB设备名称(如Abcd),当我将该设备拔下时ABCD就消失,再插上时立即可以看到,WIN2000如何知道该消息,通过什么样的APT得到

ajn_sailing(ajn_sailing)的办法虽然可行,问题是我机器上不止一个USB设备
ajn_sailing 2002-09-05
  • 打赏
  • 举报
回复
我当时是这样作的:在WM-DEVICECHANGE事件中(不知道插入或拔出),对USB设备检测10次,如果检测到则是插入USB,若检测不到是拔出USB设备
bool result;
if (message == WM_DEVICECHANGE)
{

while (!result && (i_number < 10))
{
//Sleep(1000);
i_number ++;
status = EPS_OpenDevice( &ctx, Flags );
if(status!=EPS_SUCCESS)
{

EPS_CloseDevice(&ctx);
continue;

}
else
{
result = true;
EPS_CloseDevice(&ctx) ;
break;
}

}
if (!result)
{

::MessageBox(NULL," USB钥匙被拔出,进入自动加密模式! ","提示信息",MB_OK);
SendMessage(WM_VERIFY,0,0);
}


}
heton 2002-09-03
  • 打赏
  • 举报
回复
刚少了 Setupapi.lib

我用 zhuwenzheng的方法列出以下结果

Result:[ACPI Fixed Feature Button]
Result:[System timer]
Result:[Direct memory access controller]
Result:[Standard 101/102-Key or Microsoft Natural PS/2 Keyboard]

并没有我的USB设备啊,怎么回事

heton 2002-09-03
  • 打赏
  • 举报
回复
按 bager(柏哥) 的方法,我拔出USB设备 wParam 总是=7所以没有任何反应

用 zhuwenzheng的方法,我在对话框程序里面降你的MAIN做成一个函数,编译时报错
unresolved external symbol __imp__SetupDiDestroyDeviceInfoList@4

unresolved external symbol __imp__SetupDiGetDeviceRegistryPropertyA@28
unresolved external symbol __imp__SetupDiEnumDeviceInfo@12
unresolved external symbol __imp__SetupDiGetClassDevsA@16

是不是需要什么DDK包啊?
hfycl 2002-09-02
  • 打赏
  • 举报
回复
mark
bager 2002-09-02
  • 打赏
  • 举报
回复
我用活动硬盘进行测试,可以判断它的插入或者拔出。试一下吧!

// CheckUsb.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Dbt.h"


void DeviceChangeEventOpt(WPARAM wParam, LPARAM lParam)
{
switch(wParam)
{
case DBT_CONFIGCHANGECANCELED:
MessageBox(NULL,"设备改变DBT_CONFIGCHANGECANCELED","提示",MB_OK);
break;
case DBT_CONFIGCHANGED:
MessageBox(NULL,"设备改变DBT_CONFIGCHANGED","提示",MB_OK);
break;
case DBT_CUSTOMEVENT:
MessageBox(NULL,"设备改变DBT_CUSTOMEVENT","提示",MB_OK);
break;
case DBT_DEVICEARRIVAL: // A device has been inserted and is now available.

MessageBox(NULL,"设备改变DBT_DEVICEARRIVAL","提示",MB_OK);

DEV_BROADCAST_HDR *stHDR;
stHDR = (DEV_BROADCAST_HDR *)lParam;

//判断设备类型
switch(stHDR->dbch_devicetype)
{
case DBT_DEVTYP_DEVICEINTERFACE:
MessageBox(NULL,"设备类型 DBT_DEVTYP_DEVICEINTERFACE","提示",MB_OK);
break;
case DBT_DEVTYP_HANDLE:
MessageBox(NULL,"设备类型 DBT_DEVTYP_HANDLE","提示",MB_OK);
break;
case DBT_DEVTYP_OEM:
MessageBox(NULL,"设备类型 DBT_DEVTYP_OEM","提示",MB_OK);
break;
case DBT_DEVTYP_PORT:
MessageBox(NULL,"设备类型 DBT_DEVTYP_PORT","提示",MB_OK);
break;
case DBT_DEVTYP_VOLUME:// Logical volume. This structure is a DEV_BROADCAST_VOLUME structure
MessageBox(NULL,"设备类型 DBT_DEVTYP_VOLUME","提示",MB_OK);
break;
}
//

break;
case DBT_DEVICEQUERYREMOVE:
MessageBox(NULL,"设备改变DBT_DEVICEQUERYREMOVE","提示",MB_OK);
break;
case DBT_DEVICEQUERYREMOVEFAILED:
MessageBox(NULL,"设备改变DBT_DEVICEQUERYREMOVEFAILED","提示",MB_OK);
break;
case DBT_DEVICEREMOVECOMPLETE:// A device has been removed.
MessageBox(NULL,"设备改变DBT_DEVICEREMOVECOMPLETE","提示",MB_OK);
break;
case DBT_DEVICEREMOVEPENDING://
MessageBox(NULL,"设备改变DBT_DEVICEREMOVEPENDING","提示",MB_OK);
break;
case DBT_DEVICETYPESPECIFIC://
MessageBox(NULL,"设备改变DBT_DEVICETYPESPECIFIC","提示",MB_OK);
break;
case DBT_QUERYCHANGECONFIG:
MessageBox(NULL,"设备改变DBT_QUERYCHANGECONFIG","提示",MB_OK);
break;
case DBT_USERDEFINED ://
MessageBox(NULL,"设备改变DBT_USERDEFINED","提示",MB_OK);
break;

}
}

HWND hwndMain;
LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{

switch(uMsg)
{
case WM_CREATE:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
break;
case WM_DEVICECHANGE:

DeviceChangeEventOpt(wParam,lParam);


break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.

WNDCLASSEX wclass;
MSG msg;

wclass.cbClsExtra = 0;
wclass.cbSize = sizeof(WNDCLASSEX);
wclass.cbWndExtra = 0;
wclass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH);
wclass.hCursor = NULL;
wclass.hIcon = NULL;
wclass.hIconSm = NULL;
wclass.hInstance = hInstance;
wclass.lpfnWndProc =(WNDPROC)WndProc;
wclass.lpszClassName = "CheckUSB";
wclass.lpszMenuName = NULL;
wclass.style = CS_DBLCLKS;



if(!RegisterClassEx(&wclass))
{
MessageBox(NULL,"类创建失败","类创建失败",MB_OK);
}
hwndMain = CreateWindow("CheckUSB","检测USB设备",
WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 320, 300,NULL, NULL, hInstance, NULL);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg); //translate the message into its char equivelent
DispatchMessage(&msg);
}

return msg.wParam;
}


zhuwenzheng 2002-09-02
  • 打赏
  • 举报
回复
you can try this code to detect USB device
#include <stdio.h>
#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#include <regstr.h>

int main( )
{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;

// Create a HDEVINFO with all present devices.
hDevInfo = SetupDiGetClassDevs(NULL, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES );
if (hDevInfo == INVALID_HANDLE_VALUE)
{
// Insert error handling here.
return 1;
}

// Enumerate through all devices in Set.

DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
{
DWORD DataT;
LPTSTR buffer = NULL;
DWORD buffersize = 0;

//
// Call function with null to begin with,
// then use the returned buffer size
// to Alloc the buffer. Keep calling until
// success or an unknown failure.
//
while (!SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC,
&DataT, (PBYTE)buffer, buffersize, &buffersize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
if (buffer) LocalFree(buffer);
buffer = (char *)LocalAlloc(LPTR,buffersize);
}
else
{
// Insert error handling here.
break;
}
} // while
printf("Result:[%s]\n",buffer);

if (buffer)
LocalFree(buffer);
} // for


if ( GetLastError()!=NO_ERROR && GetLastError()!=ERROR_NO_MORE_ITEMS )
{
// Insert error handling here.
return 1;
}

// Cleanup
SetupDiDestroyDeviceInfoList(hDevInfo);

return 0;
} // main lo
heton 2002-09-02
  • 打赏
  • 举报
回复
zhuwenzheng()

谢谢我看了那个帖子,可是我还是不知如何做
zhuwenzheng 2002-09-02
  • 打赏
  • 举报
回复
http://www.csdn.net/expert/topic/799/799648.xml?temp=3.387088E-02

16,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧