摘要:[C#][API]偵測USB 儲存裝置的插拔
參考此篇而成
[C#]
ManagementEventWatcher managementEventWatcher;
delegate void UpdateListBoxDelegate(string data);
UpdateListBoxDelegate updateDelegate;
private void Form1_Load(object sender, EventArgs e)
{
managementEventWatcher = new ManagementEventWatcher("Select * From __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA \"Win32_DiskDrive\"");
managementEventWatcher.Start();
managementEventWatcher.EventArrived += new EventArrivedEventHandler(managementEventWatcher_EventArrived);
updateDelegate = new UpdateListBoxDelegate(UpdateListBox);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
managementEventWatcher.Stop();
}
private void managementEventWatcher_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
{
ManagementBaseObject newEvent = e.NewEvent, newEventTarget = (newEvent["TargetInstance"] as ManagementBaseObject);
if (newEventTarget["InterfaceType"].ToString() == "USB")
{
switch (newEvent.ClassPath.ClassName)
{
case "__InstanceCreationEvent":
this.Invoke(updateDelegate, new object[] { Convert.ToString(newEventTarget["Caption"]) + " has been plugged in" });
break;
case "__InstanceDeletionEvent":
this.Invoke(updateDelegate, new object[] { Convert.ToString(newEventTarget["Caption"]) + " has been plugged out" });
break;
}
}
}
private void UpdateListBox(string data)
{
listBox1.Items.Add(data);
}
[VB]
Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
Delegate Sub UpdateListBoxDelegate(ByVal data As String)
Friend updateDelegte As UpdateListBoxDelegate
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
m_MediaConnectWatcher = New ManagementEventWatcher("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA ""Win32_DiskDrive""")
m_MediaConnectWatcher.Start()
updateDelegte = New UpdateListBoxDelegate(AddressOf UpdateListBox)
End Sub
Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
Dim newEvent, newEventTarget As ManagementBaseObject
newEvent = CType(e.NewEvent, ManagementBaseObject)
newEventTarget = CType(newEvent("TargetInstance"), ManagementBaseObject)
If newEventTarget("InterfaceType") = "USB" Then
Select newEvent.ClassPath.ClassName
Case "__InstanceCreationEvent"
Me.Invoke(updateDelegte, New Object() {Convert.ToString(newEventTarget("Caption")) & " has been plugged in"})
Case "__InstanceDeletionEvent"
Me.Invoke(updateDelegte, New Object() {Convert.ToString(newEventTarget("Caption")) & " has been plugged out"})
End Select
End If
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
m_MediaConnectWatcher.Stop()
End Sub
Private Sub UpdateListBox(ByVal data As String)
ListBox1.Items.Add(data)
End Sub