[英]Can't minimize the new Process Window on Process.Start
我需要從我的程序中啟動一個 java .jar
進程。
一旦開始,我得到 output 並處理它。
為此,我使用以下代碼:
Dim p_Process As New Process()
Dim p_p As New ProcessStartInfo
p_p.FileName = "java.exe"
p_p.Arguments = "-jar myjar.jar"
p_p.WorkingDirectory = apppath & "\myFolder"
p_p.UseShellExecute = False
p_p.RedirectStandardOutput = True
p_p.WindowStyle = ProcessWindowStyle.Minimized
AddHandler p_Process.OutputDataReceived, AddressOf manageContent
p_Process.StartInfo = p_p
p_Process.Start()
p_Process.BeginOutputReadLine()
我需要以下幾行才能獲得進程的 output 供我使用:
p_p.UseShellExecute = False
p_p.RedirectStandardOutput = True
一切正常,但 window 沒有最小化。
如何最小化 window?
一種可能的方法是最小化 Java.exe 生成的Java.exe
,當它出現時,使用 UI 自動化。
當進程啟動時,執行Jar
文件並創建新的 Window。 This Window has a specific class name, SunAwtFrame
: this value can be used to identify the window, then access the UI Automation Element's WindowPattern and call its SetWindowVisualState() method to minimize the Window.
您也可以使用 Window Title 屬性,以防它在這里是更好的選擇。 在這種情況下,識別 Window 的PropertyCondition是NameProperty而不是ClassNameProperty :
window = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(
AutomationElement.NameProperty, "[The Window Title]"))
當然,該過程是完美的功能。
在這里,我使用異步變體實現它,重定向 StandardOutput 和 StandardError,還啟用和訂閱Exited
事件,設置[Process].EnableRaisingEvents = True
。
Exited
事件會在進程關閉時發出通知,並且還會處理進程 object。
此處的代碼使用 StopWatch 來等待 Process' Window 出現,因為Process.WaitForInputIdle()
可能無法正確完成並過早完成。
如果3000
毫秒的間隔太短或太長,請調整代碼。
但是請注意,只要 Window 出現,就會退出While
循環。
此代碼需要對UIAutomationClient
和UIAutomationTypes
程序集的引用。
Imports System.Windows.Automation
Dim proc As New Process()
Dim psInfo As New ProcessStartInfo() With {
.FileName = "java.exe",
.Arguments = "-jar YourJarFile.jar",
.WorkingDirectory = "[Your Jar File Path]",
.UseShellExecute = False,
.RedirectStandardOutput = True,
.RedirectStandardError = True
}
proc.EnableRaisingEvents = True
proc.StartInfo = psInfo
AddHandler proc.OutputDataReceived,
Sub(o, ev)
Console.WriteLine(ev.Data?.ToString())
End Sub
AddHandler proc.ErrorDataReceived,
Sub(o, ev)
Console.WriteLine(ev.Data?.ToString())
End Sub
AddHandler proc.Exited,
Sub(o, ev)
Console.WriteLine("Process Exited")
proc?.Dispose()
End Sub
proc.Start()
proc.BeginOutputReadLine()
Dim window As AutomationElement = Nothing
Dim sw1 As Stopwatch = New Stopwatch()
sw1.Start()
While True
window = AutomationElement.RootElement.FindFirst(
TreeScope.Children, New PropertyCondition(
AutomationElement.ClassNameProperty, "SunAwtFrame"))
If window IsNot Nothing OrElse sw1.ElapsedMilliseconds > 3000 Then Exit While
End While
sw1.Stop()
If window IsNot Nothing Then
DirectCast(window.GetCurrentPattern(WindowPattern.Pattern), WindowPattern).
SetWindowVisualState(WindowVisualState.Minimized)
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.