首页 > 解决方案 > 如何从第 3 方 exe 获取唯一的进程 ID

问题描述

我创建了一个可以同时运行的屏幕录像机和流录像机。我正在使用 FFMPEG 执行使用 Process.Start() 函数触发的录制。现在,如果两个录制选项都在运行,我将运行 2 个 FFMPEG 程序和 2 个控制台窗口。因此,我需要能够独立地关闭或退出任一录制选项,而不会影响另一个。

到目前为止,这是我的代码......

    Dim cmdstr = "/k ffmpeg.exe -y -probesize 10M -rtbufsize 1500M -f dshow -i audio=""" & 
    Audio_name & """ -acodec pcm_s16le -f gdigrab -framerate 60 -i desktop -vcodec libx264 -qp 0 
    -threads 0 -crf 18 -preset ultrafast -tune zerolatency " & str & "\Recordings\ScreenRecorder" 
    & FileTime & ".mkv"


                If TestFF = True Then
                    MsgBox("1. Test Mode: " & cmdstr)
                    Process.Start("cmd.exe", "/k ffmpeg.exe -list_devices true -f dshow -i dummy") ' This lists all devices
                    Process.Start("cmd.exe", cmdstr)
                    RTBStreamData1.Text = cmdstr
                    RecordingInProcess = True
                    RecordingOn = True
                Else
                    Dim startInfo As New ProcessStartInfo("cmd.exe")
                    startInfo.Arguments = cmdstr
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden
                    startInfo.CreateNoWindow = True
                    startInfo.UseShellExecute = False
                    Process.Start(startInfo)
                    RecordingInProcess = True
                    RecordingOn = True
                    Dim ProcID As Integer = Process.GetCurrentProcess.Id
                    Label13.Text = ProcID.ToString

我能够获取应用程序本身的 ID,但我需要能够同时关闭的是 ffmpeg 的各个进程和相关的控制台窗口。

任何形式的帮助将不胜感激。谢谢你。

在此处输入图像描述

在上图中,您可以看到我能够跟踪第一个进程,但不能跟踪第二个进程!!!

标签: vb.netprocess

解决方案


如果我很好理解:您可以使用的一个技巧可能是将“FAKE”自定义参数传递给您将通过 Process.Start() 启动的每个进程。在循环运行进程之后,您可以识别您的目标进程。下面的代码给出了一个想法。(为了避免 SQL 注入,需要更改 SQL 字符串中的某些内容)

Dim PROCESS_CUSTOM_ARG As String = "UNIQUE_STRING_ID_HERE" '& _1  also add an integer incremental for each process

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim startInfo As New ProcessStartInfo("cmd.exe")
    startInfo.Arguments = " - a lot of your Arguments here"
    startInfo.Arguments &= " - " & PROCESS_CUSTOM_ARG
    startInfo.WindowStyle = ProcessWindowStyle.Hidden
    startInfo.CreateNoWindow = True
    startInfo.UseShellExecute = False
    Process.Start(startInfo)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim searcher As New System.Management.ManagementObjectSearcher("root\CIMV2", "SELECT ProcessId, CommandLine FROM Win32_Process WHERE CommandLine LIKE '%" & PROCESS_CUSTOM_ARG & "' ")
    For Each p As System.Management.ManagementObject In searcher.Get()
        Dim ProcessId As String = p("ProcessId")
        Dim CommandLine As String = p("CommandLine")
        Console.WriteLine($"CommandLine: {CommandLine} ProcessId: {ProcessId}")
        Dim Proc As Process = Process.GetProcessById(ProcessId)
        Proc.Kill()
    Next
End Sub

推荐阅读