关闭IE并打开Chrome,只运行一次,然后崩溃
问题描述:
我有以下非常简单的脚本关闭IE并打开Chrome,只运行一次,然后崩溃
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
打开一个IE窗口时,这应监测,关闭和运行铬代替。这工作第一次很好,但一旦它完成它崩溃与以下错误
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.
我该怎么做才能阻止COM从分离?我希望程序从Windows开始,并继续运行。
感谢
答
我解决了这个问题可基本建立循环
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
不是循环。这是一个递归调用,如果此程序要运行一段时间,它最终可能会导致问题。特别是堆栈溢出。你可以使用while循环来代替递归。 – theB
谢谢,今天监测它,看看我是否遇到任何问题。 – dave