Normally the autorun in usb storage devices like pendrives is disabled for security reasons, so i wrote a little utility in c++ to launch a custom application in my pendrive when I insert it in a usb port.

Logo usb

Normally if you want to detect when a “hotplug” device has been inserted or removed from your system, you have to intercept the system message “WM_DEVICECHANGE” in “WndProc” function of the main window of your application.
Each window must request notify to the system, calling the function RegisterDeviceNotification, to receive the “WM_DEVICECHANGE” message; but if you want to detect the actions of an “usb mass storage device” you don’t need to call this function, because the system send it automatically in broadcast to all windows.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
		case WM_PAINT:
			......
			break;
		case WM_DEVICECHANGE:
			return Main_OnDeviceChange(hWnd,wParam,lParam);
			break;
		default:
			....
	}
}

If you want to know exactly if a device has been inserted, safely removed, or if other specific actions has happened, you can use this function:

LRESULT Main_OnDeviceChange (HWND hwnd, WPARAM wParam, LPARAM lParam)
{
	PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
	switch(wParam)
	{
		case DBT_DEVICEARRIVAL:
		{
			... //A device has been inserted.
			break;
		}
		case DBT_DEVICEREMOVECOMPLETE:
		{
			... //A device has been removed.
			break;
		}
		default:
		{}
	}
}

Se sei interessato a questo post, potresti anche provare a leggere:

  • No related posts