是否有一种简单的方法可以让DirectShow检测网络摄像头是否已插入(USB),或者有人拔掉它(然后轮询或搜索)?
我见过Microsoft Media Foundation的代码,但它很复杂,并且Media Foundation不能安装在< Vista,afaik。
Thx,WW
答案 0 :(得分:1)
我使用WMI事件观察器在属性字符串中查找PID(某些摄像机可能会根据驱动程序触发事件两次)。这是一个VB.Net示例:
Dim CamEventWatcher As ManagementEventWatcher
Public Delegate Sub SetMessageCallback(ByVal [_Msg] As Boolean)
Private Sub MessageCallback(ByVal _Msg As Boolean)
If (_Msg) Then
'cam connected
Else
'camera removed
End If
End Sub
Private Sub RemoveCameraUSBHandler()
Try
If Not CamEventWatcher Is Nothing Then
CamEventWatcher.Stop()
End If
Catch ex As Exception
End Try
End Sub
Private Sub AddCameraUSBHandler()
Dim q As WqlEventQuery
Dim scope As ManagementScope = New ManagementScope("root\CIMV2")
scope.Options.EnablePrivileges = True
Try
q = New WqlEventQuery()
q.EventClassName = "__InstanceOperationEvent"
q.WithinInterval = New TimeSpan(0, 0, 1)
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"
CamEventWatcher = New ManagementEventWatcher(scope, q)
AddHandler CamEventWatcher.EventArrived, AddressOf CamUSBEvent
CamEventWatcher.Start()
Catch ex As Exception
End Try
End Sub
Private iCreatedFired As Integer = 0
Private iRemovedFired As Integer = 0
Public Sub CamUSBEvent(ByVal sender As System.Object, ByVal e As EventArrivedEventArgs)
If e.NewEvent.ClassPath.ClassName = "__InstanceCreationEvent" Then
Dim sAntecedent As String
Dim sDependent As String
sAntecedent = e.NewEvent.Properties("TargetInstance").Value.Properties("Antecedent").Value.ToString() + ControlChars.CrLf
sDependent = e.NewEvent.Properties("TargetInstance").Value.Properties("Dependent").Value.ToString() + ControlChars.CrLf
If sDependent.Contains(CAM_DEV_ID) Then
iCreatedFired += 1
If (iCreatedFired = 1) Then
e.NewEvent.Dispose()
Return
End If
iCreatedFired = 0
iRemovedFired = 0
Dim _delegate As New SetMessageCallback(AddressOf MessageCallback)
Me.Invoke(_delegate, New Object() {True})
End If
ElseIf e.NewEvent.ClassPath.ClassName = "__InstanceDeletionEvent" Then
Dim sAntecedent As String
Dim sDependent As String
sAntecedent = e.NewEvent.Properties("TargetInstance").Value.Properties("Antecedent").Value.ToString() + ControlChars.CrLf
sDependent = e.NewEvent.Properties("TargetInstance").Value.Properties("Dependent").Value.ToString() + ControlChars.CrLf
If sDependent.Contains(CAM_DEV_ID) Then
iRemovedFired += 1
If (iRemovedFired = 1) Then
e.NewEvent.Dispose()
Return
End If
iCreatedFired = 0
iRemovedFired = 0
Dim _delegate As New SetMessageCallback(AddressOf MessageCallback)
Me.Invoke(_delegate, New Object() {False})
End If
End If
e.NewEvent.Dispose()
End Sub