【问题标题】:Give a custom name to a process started in VB.Net为在 VB.Net 中启动的进程提供自定义名称
【发布时间】:2018-09-04 14:08:25
【问题描述】:

当在 VB.Net 中启动一个进程时,我想给它一个自定义名称,该名称可由我将此进程作为参数的任何函数访问。

我以这种方式启动我的流程:

Dim mainProcessHandler As New ProcessStartInfo()
Dim mainProcess As Process
mainProcessHandler.FileName = "something_01out18.bat"
mainProcessHandler.Arguments = "-d"
mainProcessHandler.WindowStyle = ProcessWindowStyle.Hidden
mainProcess = Process.Start(mainProcessHandler)

如果我什么都不做,在使用时

mainProcess.ProcessName

我会得到“cmd”,因为它是一个由 cmd 运行的 bat 脚本。

我可以做类似的事情

mainProcess.myCustomName = "bat01out18"

并在函数中调用它

Sub doThingsWithProcess(ByVal usedForThingsProcess As Process) As Boolean
    infoConsoleDisplay("process " + usedForThingsProcess.myCustomName + " will be used to for things")
End Sub

我很确定有一种方法可以实现这样的目标,但可能采用不同的方法。你有什么想法吗?

【问题讨论】:

标签: vb.net process unique


【解决方案1】:

您可以创建一个继承自Process 的子类,然后您可以向其中添加任何您喜欢的自定义属性。这是一个例子:

Public Class CustomProcess
    Inherits Process

    Public Property DisplayName As String

End Class

用法:

Dim pInfo As New ProcessStartInfo()
pInfo.FileName = "cmd.exe"
pInfo.Arguments = "/C ping 127.0.0.1"
pInfo.WindowStyle = ProcessWindowStyle.Normal
Dim mainProcess As New CustomProcess() With {.DisplayName = "MyProcess"}
mainProcess.StartInfo = pInfo
mainProcess.Start()

Console.WriteLine($"Process '{mainProcess.DisplayName}' will be doing so and so.")

输出:

Process 'MyProcess' will be doing so and so.

【讨论】:

  • 这解决了我的问题。我在每个 mainProcess.StartInfo = mainProcessStartInfo mainProcess.Start() 之前设置了一个 mainProcess.DisplayName = "Process doing that"
  • @JulienD 没错,或者你可以使用对象初始化器(即With {.DisplayName = "MyProcess"}),如答案所示。
  • 当然,但是由于我多次为不同的 bat 脚本使用相同的 mainProcess 实例,因此我需要随着时间的推移覆盖 DisplayName。谢谢。
猜你喜欢
  • 2021-07-07
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
相关资源
最近更新 更多