473,386 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Detecting USB Stick Plug in and Plug out (USB Harddrive)

Hi,
I'm looking for a solution to detect if a USB Sticker (USB Drive) ist
plugged in or plugged out. Currently Im able to detect Hardware Plugin
and Plugout but don't get any information what type of device it is.
Is there a way to get this information ?
Currenty my solution work in that way (Also from this group):

protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
}

base.WndProc (ref m);
}

void OnDeviceChange(ref Message msg)
{
int wParam = (int)msg.WParam;

if(wParam == Win32.DBT_DEVICEARRIVAL)
{
statusBar.Text = "Hardware attached";
frmLockScreen.Close();
}
else if(wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
{
statusBar.Text = "Hardware entfernt";

frmLockScreen.Show();
}
}
void RegisterHidNotification()
{
Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
Win32.DEV_BROADCAST_DEVICEINTERFACE();
int size = Marshal.SizeOf(dbi);
dbi.dbcc_size = size;
dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
dbi.dbcc_reserved = 0;
dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
dbi.dbcc_name = 0;
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(dbi, buffer, true);
IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
if(r == IntPtr.Zero)
Console.WriteLine(Win32.GetLastError().ToString()) ;
}

class Win32
{
public const int
WM_DEVICECHANGE = 0x0219;
public const int
DBT_DEVICEARRIVAL = 0x8000,
DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int
DEVICE_NOTIFY_WINDOW_HANDLE = 0,
DEVICE_NOTIFY_SERVICE_HANDLE = 1;
public const int
DBT_DEVTYP_DEVICEINTERFACE = 5;
public static Guid
GUID_DEVINTERFACE_HID = new
Guid("4D1E55B2-F16F-11CF-88CB-001111000030");

[StructLayout(LayoutKind.Sequential)]
public class DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
public short dbcc_name;
}

[DllImport("user32.dll", SetLastError=true)]
public static extern IntPtr RegisterDeviceNotification(
IntPtr hRecipient,
IntPtr NotificationFilter,
Int32 Flags);

[DllImport("kernel32.dll")]
public static extern int GetLastError();
}
Thanks for any hints,
daniel
Nov 15 '05 #1
1 18310
Much better is to use the System.Management classes and register event
listeners for Win32_Diskdrive class operations.

Here's a small console sample.

// This code demonstrates how to monitor the UsbControllerDevice for
// the arrival of creation/operation events
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Management;
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
ManagementOperationObserver observer = new ManagementOperationObserver();
// Bind to local machine
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true; //set required privilege
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.WithinInterval = new TimeSpan(0,0,3);
q.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";
w = new ManagementEventWatcher(scope, q);

w.EventArrived += new EventArrivedEventHandler(we.DiskEventArrived);
w.Start();
Console.ReadLine(); // block main thread for test purposes
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
finally {
w.Stop();
}
}
public void DiskEventArrived(object sender, EventArrivedEventArgs e) {
//Get the Event object and display its properties (all)
foreach(PropertyData pd in e.NewEvent.Properties) {
ManagementBaseObject mbo = null;
if(( mbo = pd.Value as ManagementBaseObject) != null) {
Console.WriteLine("--------------Properties------------------");
foreach(PropertyData prop in mbo.Properties)
Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
}
}
}

}
Willy.

"Daniel Diehl" <da****@mediaworker.net> wrote in message
news:33**************************@posting.google.c om...
Hi,
I'm looking for a solution to detect if a USB Sticker (USB Drive) ist
plugged in or plugged out. Currently Im able to detect Hardware Plugin
and Plugout but don't get any information what type of device it is.
Is there a way to get this information ?
Currenty my solution work in that way (Also from this group):

protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
}

base.WndProc (ref m);
}

void OnDeviceChange(ref Message msg)
{
int wParam = (int)msg.WParam;

if(wParam == Win32.DBT_DEVICEARRIVAL)
{
statusBar.Text = "Hardware attached";
frmLockScreen.Close();
}
else if(wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
{
statusBar.Text = "Hardware entfernt";

frmLockScreen.Show();
}
}
void RegisterHidNotification()
{
Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
Win32.DEV_BROADCAST_DEVICEINTERFACE();
int size = Marshal.SizeOf(dbi);
dbi.dbcc_size = size;
dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
dbi.dbcc_reserved = 0;
dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
dbi.dbcc_name = 0;
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(dbi, buffer, true);
IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
if(r == IntPtr.Zero)
Console.WriteLine(Win32.GetLastError().ToString()) ;
}

class Win32
{
public const int
WM_DEVICECHANGE = 0x0219;
public const int
DBT_DEVICEARRIVAL = 0x8000,
DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int
DEVICE_NOTIFY_WINDOW_HANDLE = 0,
DEVICE_NOTIFY_SERVICE_HANDLE = 1;
public const int
DBT_DEVTYP_DEVICEINTERFACE = 5;
public static Guid
GUID_DEVINTERFACE_HID = new
Guid("4D1E55B2-F16F-11CF-88CB-001111000030");

[StructLayout(LayoutKind.Sequential)]
public class DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
public short dbcc_name;
}

[DllImport("user32.dll", SetLastError=true)]
public static extern IntPtr RegisterDeviceNotification(
IntPtr hRecipient,
IntPtr NotificationFilter,
Int32 Flags);

[DllImport("kernel32.dll")]
public static extern int GetLastError();
}
Thanks for any hints,
daniel

Nov 15 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Daniel Diehl | last post by:
Hi, I'm looking for a solution to detect if a USB Sticker (USB Drive) ist plugged in or plugged out. Currently Im able to detect Hardware Plugin and Plugout but don't get any information what type...
2
by: ellisydjogra | last post by:
i have down loaded net framework 1.1 but i still can not get my usb2.0 menory stick to work on my computer? any idea's pls?
0
by: Stijn | last post by:
I wrote an application where the user needs an USB memory stick. When the user closes the program, some data is written to the stick. Can I write some code so my application is closing the usb...
10
by: Joe Macarony | last post by:
Hi to theForcesOfCpp!I'm just wondering if there is any simple way to read the serial number of an memory stick connected to an USB port? Something like reading the vendor number of a hard disk......
12
by: hufaunder | last post by:
I often find myself in the situation where at a customers site I have to do some quick debugging or program changes. Obvioiusly, I do not want to install VS2005 on their system. Is there a ways to...
1
by: flamingskullz | last post by:
Hi all, firstly i apologise if this has appearred before, i did search for it, honest :) i have a sandisk memory stick, which works great at work, but as soon as i plug it into my home machine, it...
1
by: rajeshrocks2006 | last post by:
Hi, i need help in detecting usb port in a network and have to provide authentication for the USB port for the system security purposes...plzz help me....
1
by: =?Utf-8?B?Y2FsZGVyYXJh?= | last post by:
Dear all, For one on my customer application I would like to implement the following facilities: As soon as USB stick is inserted I need to run a small application which will take care of...
2
by: ashishchauhan | last post by:
I am using a linux machine with an USB port and I have to communicate with a temperature controller which has an UART port and for this I am using a USB to UART Serial Adapter. port name on my...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.