VB.NET 检测外部进程是否打开,是则关闭

问题描述 投票:0回答:1

我有一个使用以下代码调用外部可执行文件的应用程序。

Try
    'Call Process 
    Dim ProcessPath As String = "C:\Temp\"
    Dim commandStr As String = "arg1 arg2"
    startInfo.FileName = ProcessPath & "application.exe"
    startInfo.Arguments = commandStr
    startInfo.WindowStyle = ProcessWindowStyle.Hidden
    ApplicationProcess = Process.Start(startInfo)
Catch ex As Exception
    ApplicationProcess.Kill()
End Try

应用程序将文档转换为RTF文档,但有时会出现错误的文档。该应用程序实际上是一个窗口应用程序,但使用参数,我可以禁止窗口显示。但是,如果文档的格式不正确,则应用程序会显示窗口警报(见下文)。在任务管理器中,有一大堆实例占用内存。

enter image description here

.NET 如何处理 Process.Start() 函数?当 Process.Start() 行执行时,主应用程序是否会暂停并在外部应用程序完成后继续?或者被调用的外部应用程序是否在另一个线程中打开并且主应用程序继续?

如何检测警报是否已打开然后将其关闭?

vb.net
1个回答
0
投票

使用spy++查找错误对话框的窗口类。

在 FindWindow 调用中,将“#32770”替换为其类名,将“error”替换为其标题(如果适用)。

FindWindowEx 调用是可选的,但其目的是确保我们拥有正确的对话框。

Private Sub CloseErrorDialog()
     Const BM_CLICK = &HF5
     Try
         Dim errorHwnd = FindWindow("#32770", "error")
         If errorHwnd Then
             If FindWindowEx(errorHwnd, Nothing, "Static", "Error while reading file") <> IntPtr.Zero Then
                 ' you either find the button and send it a click
                 Dim butHandle = FindWindowEx(errorHwnd, Nothing, "Button", "OK")
                 SendMessage(butHandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero)
                 Debug.Print("Error dialog closed")
                 ' or you send a process kill
             End If
         End If
     Catch
         Debug.Print("CloseErrorDialog Exception")
     End Try
End Sub
 
<DllImport("user32.dll", SetLastError:=True, CharSet:=Runtime.InteropServices.CharSet.Auto)>
Public Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr : End Function

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Public Function FindWindowEx(ByVal parentHandle As IntPtr,
                  ByVal childAfter As IntPtr,
                  ByVal lclassName As String,
                  ByVal windowTitle As String) As IntPtr
End Function

您现在可以在计时器等中定期调用 CloseErrorDialog()

© www.soinside.com 2019 - 2024. All rights reserved.