Saturday, January 21, 2017

Check for usb-sticks in windows

Hi,

I wanted to check in my app whether usb sticks are connected or not (automatic recognition)...

Some research later I found the following article:

https://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives

works quite straight forward ...

things to mention:
- for different use-cases it might be enough to check Win32_LogicalDisk where drivetype=2

- in wpf you might use something like:

1
2
3
4
5
6
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);
        }

- when you disconnect a stick and call the wmi to show you data Win32_DiskDrive / Win32_LogicalDisk you get exception ... sleep and retry works after about 5 seconds.

- you can check the result in command line using "wmic logicaldisk get"

kr,
Daniel

1 comment:

Daniel Kienböck said...

related:

https://www.codeproject.com/Tips/1185385/How-to-Detect-When-Your-USB-Device-Has-Been-Plugge