Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?
当驱动器号可以访问时,是否可以获得通知(无需轮询,但通过事件)。例如,如果您的外部硬盘驱动器始终显示为驱动器F - 是否可以在连接时引发事件并且可以访问F?
2 个解决方案
#1
1
Okay.. found what I was looking for :)
好的..发现我在寻找:)
Take a look at this VBScript: (source):
看看这个VBScript :(来源):
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecNotificationQuery _
("Select * From __InstanceOperationEvent Within 10 Where " _
& "TargetInstance isa 'Win32_LogicalDisk'")
Do While True
Set objEvent = colEvents.NextEvent
If objEvent.TargetInstance.DriveType = 2 Then
Select Case objEvent.Path_.Class
Case "__InstanceCreationEvent"
Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
" has been added."
Case "__InstanceDeletionEvent"
Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
" has been removed."
End Select
End If
Loop
I leave it to your exercise to port it to C#.
我把它留给你的练习,把它移植到C#。
Instead of polling all the time you can use a WMI event sink.
您可以使用WMI事件接收器而不是一直轮询。
#2
1
You can wait for the WM_DEVICECHANGE message, all the details are at:
您可以等待WM_DEVICECHANGE消息,所有细节都在:
http://msdn.microsoft.com/en-us/library/aa363215(VS.85).aspx
You're going to have to create a window to receive this message, the window can be hidden if you need, to get this message in WinForms just override the Form.WndProc method
您将不得不创建一个窗口来接收此消息,如果需要可以隐藏窗口,在WinForms中获取此消息只是覆盖Form.WndProc方法
#1
1
Okay.. found what I was looking for :)
好的..发现我在寻找:)
Take a look at this VBScript: (source):
看看这个VBScript :(来源):
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecNotificationQuery _
("Select * From __InstanceOperationEvent Within 10 Where " _
& "TargetInstance isa 'Win32_LogicalDisk'")
Do While True
Set objEvent = colEvents.NextEvent
If objEvent.TargetInstance.DriveType = 2 Then
Select Case objEvent.Path_.Class
Case "__InstanceCreationEvent"
Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
" has been added."
Case "__InstanceDeletionEvent"
Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
" has been removed."
End Select
End If
Loop
I leave it to your exercise to port it to C#.
我把它留给你的练习,把它移植到C#。
Instead of polling all the time you can use a WMI event sink.
您可以使用WMI事件接收器而不是一直轮询。
#2
1
You can wait for the WM_DEVICECHANGE message, all the details are at:
您可以等待WM_DEVICECHANGE消息,所有细节都在:
http://msdn.microsoft.com/en-us/library/aa363215(VS.85).aspx
You're going to have to create a window to receive this message, the window can be hidden if you need, to get this message in WinForms just override the Form.WndProc method
您将不得不创建一个窗口来接收此消息,如果需要可以隐藏窗口,在WinForms中获取此消息只是覆盖Form.WndProc方法