请给我一个demo
时间: 2024-02-28 12:55:58 浏览: 144
以下是一个使用 RegisterDeviceNotification 函数获取新插入设备盘符的简单示例:
```c++
#include <windows.h>
#include <dbt.h>
#include <iostream>
#include <vector>
using namespace std;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 创建窗口
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hWnd = CreateWindowEx(
0,
CLASS_NAME,
L"Sample Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL
);
if (hWnd == NULL)
{
return 0;
}
// 注册设备通知
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter = {};
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
HDEVNOTIFY hDevNotify = RegisterDeviceNotification(hWnd, &NotificationFilter,
DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
// 处理消息循环
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 注销设备通知
UnregisterDeviceNotification(hDevNotify);
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DEVICECHANGE:
if (wParam == DBT_DEVICEARRIVAL)
{
// 获取当前系统中所有逻辑驱动器
wchar_t Drives[128];
ZeroMemory(Drives, 128 * sizeof(wchar_t));
GetLogicalDriveStrings(128, Drives);
// 将驱动器列表转换为 vector 类型
vector<wstring> DriveList;
wchar_t* p = Drives;
while (*p)
{
DriveList.push_back(p);
p += wcslen(p) + 1;
}
// 查找新插入的驱动器盘符
DEV_BROADCAST_DEVICEINTERFACE* pDev = (DEV_BROADCAST_DEVICEINTERFACE*)lParam;
wstring DeviceName = pDev->dbcc_name;
size_t pos = DeviceName.find_last_of(L'\\');
wstring DeviceID = DeviceName.substr(pos + 1);
wchar_t DriveLetter = 0;
for (wchar_t c = L'C'; c <= L'Z'; c++)
{
wstring DrivePath = wstring(1, c) + L":\\";
if (find(DriveList.begin(), DriveList.end(), DrivePath) == DriveList.end())
{
// 驱动器不存在,说明是新插入的设备
DriveLetter = c;
break;
}
}
if (DriveLetter != 0)
{
wcout << L"New device inserted: " << DriveLetter << L":" << endl;
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
在上述示例中,我们创建了一个窗口,并在窗口创建完成后使用 RegisterDeviceNotification 函数注册设备通知。在处理 WM_DEVICECHANGE 消息时,我们首先使用 GetLogicalDriveStrings 函数获取当前系统中所有逻辑驱动器的列表,然后通过比较新插入设备的设备 ID 和驱动器列表,找出新插入的驱动器盘符。最后,我们使用 wcout 输出新插入设备的盘符。
阅读全文