Skip to content

Instantly share code, notes, and snippets.

@gavxin
Last active December 4, 2018 15:41
Show Gist options
  • Save gavxin/5e322cb17aafea85e522e0fca3aac7d3 to your computer and use it in GitHub Desktop.
Save gavxin/5e322cb17aafea85e522e0fca3aac7d3 to your computer and use it in GitHub Desktop.
USB storage device plug event detection.
#include <Windows.h>
#include <Dbt.h>
#include "resource.h"
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam,
LPARAM lParam) {
switch (uMsg) {
case WM_DEVICECHANGE:
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
switch (pHdr->dbch_devicetype) {
case DBT_DEVTYP_VOLUME: {
PDEV_BROADCAST_VOLUME pDevVolume = (PDEV_BROADCAST_VOLUME)pHdr;
for (int i = 0; i < 26; i++) {
if (pDevVolume->dbcv_unitmask & (1 << i)) {
char letter = 'A' + i;
if (DBT_DEVICEARRIVAL == wParam) {
// Plug in. volume drive letter is in var 'letter'
} else if (DBT_DEVICEREMOVECOMPLETE == wParam) {
// Plug out. volume drive letter is in var 'letter'
}
}
}
break;
}
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCANCEL:
SendMessage(hDlg, WM_CLOSE, 0, 0);
return TRUE;
}
break;
case WM_CLOSE:
if (MessageBox(hDlg, TEXT("Close the program?"), TEXT("Close"),
MB_ICONQUESTION | MB_YESNO) == IDYES) {
DestroyWindow(hDlg);
}
return TRUE;
case WM_DESTROY:
PostQuitMessage(0);
return TRUE;
}
return FALSE;
}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE h0, LPSTR lpCmdLine, int nCmdShow) {
HWND hDlg;
MSG msg;
BOOL ret;
// Need add a resource, add a dialog.
hDlg =
CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_DIALOG1), 0, DialogProc, 0);
ShowWindow(hDlg, SW_HIDE);
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
if (ret == -1) return -1;
if (!IsDialogMessage(hDlg, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment