【问题标题】:Close IE and Open Chrome, only runs once and then crashes关闭 IE 并打开 Chrome,只运行一次然后崩溃
【发布时间】:2016-06-07 10:36:39
【问题描述】:

我有以下非常简单的脚本

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 窗口打开时应该监控,关闭它并运行 chrome。这第一次效果很好,但是一旦完成它就会崩溃并出现以下错误

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 启动并一直持续运行。

谢谢

【问题讨论】:

    标签: vb.net managementeventwatcher


    【解决方案1】:

    我解决了这个问题,基本上是创建一个循环

    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 循环而不是递归。
    • 谢谢,今天我会监视它,看看我是否遇到任何问题。
    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多