Here are the steps needed to add this functionality into your program without worrying about how it works:
* Add the source code (DriveDetector.cs) to your project and add using Dolinay; directive to your Form's source code.
* Create an instance of the DriveDetector class in your form. See example below.
* Add handlers for the events exposed by DriveDetector, that is for DeviceArrived, DeviceRemoved and QueryRemove.
Collapse | Copy Code
public partial class Form1 : Form
{
private DriveDetector driveDetector = null;
public Form1()
{
InitializeComponent();
driveDetector = new DriveDetector();
driveDetector.DeviceArrived += new DriveDetectorEventHandler(
OnDriveArrived);
driveDetector.DeviceRemoved += new DriveDetectorEventHandler(
OnDriveRemoved);
driveDetector.QueryRemove += new DriveDetectorEventHandler(
OnQueryRemove);
...
* Implement these handlers as shown here. You can simply copy and paste this block of source code to your Form class.
Collapse | Copy Code
// Called by DriveDetector when removable device in inserted
private void OnDriveArrived(object sender, DriveDetectorEventArgs e)
{
// e.Drive is the drive letter, e.g. "E:\\"
// If you want to be notified when drive is being removed (and be
// able to cancel it),
// set HookQueryRemove to true
e.HookQueryRemove = true;
}
// Called by DriveDetector after removable device has been unplugged
private void OnDriveRemoved(object sender, DriveDetectorEventArgs e)
{
// TODO: do clean up here, etc. Letter of the removed drive is in
// e.Drive;
}
// Called by DriveDetector when removable drive is about to be removed
private void OnQueryRemove(object sender, DriveDetectorEventArgs e)
{
// Should we allow the drive to be unplugged?
if (MessageBox.Show("Allow remove?", "Query remove",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
e.Cancel = false; // Allow removal
else
e.Cancel = true; // Cancel the removal of the device
}
That's all. Your event handlers should now be called whenever a flash drive is inserted or removed.
In this default implementation DriveDetector will create a hidden form, which it will use to receive notification messages from Windows. You could also pass your form to DriveDetector's constructor to avoid this extra (although invisible) form. To do this, just create your DriveDetector object using the second constructor:
driveDetector = new DriveDetector(this);
But then you also have to override WndPRoc method in your Form's code and call DriveDetector's WndProc from there. Again, you can just copy-paste the code below to your Form1.cs.
protected override void WndProc(ref Message m)
{
base.WndProc(ref m); // call default p
if (driveDetector != null)
{
driveDetector.WndProc(ref m);
}
}