c++ - 如何在 C/C++ 中检查 USB 是否插入或移除

标签 c++ c windows events usb

我想为Windows 7制作一个程序,在C/C++中始终检查是否有USB插入或USB移除,我该怎么做?,你能给一个示例代码吗?,谢谢

最佳答案

它有效,谢谢大家,这是代码:

#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, &notifyFilter,
#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

关于c++ - 如何在 C/C++ 中检查 USB 是否插入或移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22440308/

相关文章:

c - 有没有办法通过 union 访问各个位?

c - 编译器的语义阶段

内部循环不断增长的嵌套循环的复杂性

Windows 批处理文件删除早于 X 天的文件,但保留最少的 X 个文件

c++ - 从 CreateTool32Help api 隐藏线程

c++ - 粒子系统:所有粒子都沿相同方向移动

c# - 从 C++ 应用程序调用 C# .NET 服务?

django - 在 Windows 上正确设置 DJANGO_SETTINGS_MODULE

c++ - 如何从函数创建和返回字符串?

c++ - 使用SSE最快缩小8位灰度图像