I have the below very simple script
Imports System.Management
Imports System
Module Module1
Dim watcher As ManagementEventWatcher
Sub Main()
Dim monitoredProcess = "iexplore.exe"
Dim query As WqlEventQuery = New WqlEventQuery("__InstanceCreationEvent", New TimeSpan(0, 0, 1), "TargetInstance isa ""Win32_Process"" And TargetInstance.Name = """ & monitoredProcess & """")
watcher = New ManagementEventWatcher()
watcher.Query = query
watcher.Start()
watcher.WaitForNextEvent()
For Each p As Process In Process.GetProcessesByName("iexplore")
p.Kill()
Next
Process.Start(New System.Diagnostics.ProcessStartInfo("Chrome", "http://google.com"))
End Sub
End Module
Which should monitor when an ie window is opened, close it and run chrome instead. This works great the first time, but once it has completed it crashes with the following error
An unhandled exception of type 'System.Runtime.InteropServices.InvalidComObjectException' occurred in System.Management.dll
Additional information: COM object that has been separated from its underlying RCW cannot be used.
What can I do to stop the com from separating? I would like the program to start with windows and continue to run all the time.
Thanks
I fixed this be basically creating a loop
Imports System.Management
Imports System
Module Module1
Dim watcher As ManagementEventWatcher
Sub Main()
Dim monitoredProcess = "iexplore.exe"
Dim query As WqlEventQuery = New WqlEventQuery("__InstanceCreationEvent", New TimeSpan(0, 0, 1), "TargetInstance isa ""Win32_Process"" And TargetInstance.Name = """ & monitoredProcess & """")
watcher = New ManagementEventWatcher()
watcher.Query = query
watcher.Start()
watcher.WaitForNextEvent()
For Each p As Process In Process.GetProcessesByName("iexplore")
p.Kill()
Next
Process.Start(New System.Diagnostics.ProcessStartInfo("Chrome", "http://google.com"))
watcher.Stop()
watcher.Dispose()
Main()
End Sub
End Module