我如何检查是否有USB插入或USB移除在C/ c++
How I could check if there is a USB inserted or USB removal in C/C++
我想为windows 7做一个程序,检查所有的时间,如果有USB插入或USB移除在C/c++,我怎么能做到这一点?你能给出一个示例代码吗?
它工作了,谢谢大家,这是代码:
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <dbt.h>
#include <iostream>
#include <iomanip>
using namespace std;
#define USE_CDROM_GUID_ONLY
//-----------------------------------------------------------------------------
MSG msg;
void pupu(HWND hwnd);
LRESULT CALLBACK WinProc(HWND hwnd, UINT msg,WPARAM wParam, LPARAM lParam)
{
if (msg == WM_DEVICECHANGE)
{
switch (wParam){
case DBT_DEVICEARRIVAL:
printf("new device connected n");
break;
case DBT_DEVICEREMOVECOMPLETE:
printf("a device has been removed n");
break;
}
}//if
else
cout << "Got msg " << msg << ", " << int(wParam)
<< ", " << int(lParam) << endl;
return 1;
}//WinProc
//-----------------------------------------------------------------------------
HWND pipi(){
const char *className = "DevNotifyTest";
WNDCLASSA wincl = { 0 };
wincl.hInstance = GetModuleHandle(0);
wincl.lpszClassName = className;
wincl.lpfnWndProc = WinProc;
HWND parent = 0;
#ifdef USE_MESSAGE_ONLY_WINDOW
parent = HWND_MESSAGE;
#endif
HWND hwnd = CreateWindowExA(WS_EX_TOPMOST, className, className,0, 0, 0, 0, 0, parent, 0, 0, 0);
GUID cdromDevIntGuid =
{ 0x53F56308, 0xB6BF, 0x11D0,
{ 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B } };
DEV_BROADCAST_DEVICEINTERFACE_A notifyFilter = { 0 };
notifyFilter.dbcc_size = sizeof(notifyFilter);
notifyFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
notifyFilter.dbcc_classguid = cdromDevIntGuid;
HDEVNOTIFY hDevNotify =
RegisterDeviceNotificationA(hwnd, ¬ifyFilter,
#ifndef USE_CDROM_GUID_ONLY
DEVICE_NOTIFY_ALL_INTERFACE_CLASSES |
#endif
DEVICE_NOTIFY_WINDOW_HANDLE);
return hwnd;
}
void pupu(HWND hwnd){
BOOL bRet = PeekMessage(&msg, hwnd, 0, 0, PM_NOREMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
Sleep(1000);
}
int main()
{
HWND hwnd = pipi();
for (;;){
pupu(hwnd);
Sleep(1000);
}
return 0;
}//main
注册设备通知是一个设备通知示例。
RegisterDeviceNotification函数,注册接收来自系统的通知消息。
检测媒体插入或删除Windows发送WM_DEVICECHANGE消息到顶级窗口,当新的设备或媒体被添加和可用,当现有的设备或媒体被删除。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- Visual Studio 2019:插入多个C++风格的单行注释
- nlohmann-json将一个数组插入到另一个数组中
- 有效地使用std::unordered_map来插入或增加键的值
- 插入或删除时获取usb的dos_name
- 如何测试 USB HID 句柄由于设备被重新插入而无效
- 插入加密的 USB 驱动器后,如何使用 WMI 查找"启动器"逻辑磁盘?
- C 控制台应用程序检测USB是否插入
- C++MFC将文件写入插入的USB驱动器
- 如何在插入 USB 时触发事件
- 插入USB后自动运行
- 在C++非GUI应用程序中检测USB插入/删除
- 使用哪个代码片段来处理USB设备插入
- 我如何检查是否有USB插入或USB移除在C/ c++