在继续 VB.NET 之前等待特定程序打开 [英] Wait for a specefic program to open before continue VB.NET
问题描述
好的,正如你在下面的代码中看到的,我有一个简单的 try 语句.每当我打开该工具时,它都会寻找一个名为 csgo 的进程,如果有一个进程,它将继续使用该工具,否则它只会发送一个 MsgBox 并退出该工具.
Alright, as you see in the code down below I've got a simple try statement. Whenever I open the tool it will look for a process named csgo, if there is a process it will continue with the tool else it will just send a MsgBox and exit the tool.
但是,我希望它检查是否有 csgo 进程正在运行,如果它正在运行,它应该像现在一样继续运行,但是如果没有名为 csgo 的进程正在运行,我想制作该工具休眠并循环直到找到名为 csgo 的进程.
However, I want it for it to check if there is a csgo process running, if it's running it should continue like it is now, but if there isn't a process named csgo running I'd like to make the tool Sleep and loop til it finds a process named csgo.
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
gameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Catch ex As Exception
MsgBox("Please Start CS:GO before opening this tool")
Environment.Exit(0)
End Try
我试过这样做,效果很好,哈哈,有没有更好的方法?
I tried doing like this, and it works lol, is there a better way of doing this?
Dim Found = 0
While Found = 0
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
cgameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Found = 1
Catch ex As Exception
MsgBox("Waiting for csgo to launch.")
Threading.Thread.Sleep(1000)
End Try
End While
推荐答案
假设这是一个控制台应用程序,您可以对现有应用程序进行一些改进.
Assuming this is a console application, you can make some improvements over what you have.
' Use a boolean for binary logic.
' This takes up 1 bit whereas your Int32 took up 32 bits
Dim allDone = False
While Not allDone
Try
Dim processes = Process.GetProcessesByName("csgo")
If processes.Count > 0 Then
csgoProcess = processes(0)
Dim handle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
If handle IsNot Nothing Then
allDone = True
End If
Else
' Use a Retry / Cancel MsgBox to allow the user to retry or cancel
' Clicking Cancel will now exit the application
Select Case MsgBox("Waiting for csgo to launch.",
MsgBoxStyle.RetryCancel, "Confirm retry")
Case MsgBoxResult.Retry
Threading.Thread.Sleep(1000)
Case MsgBoxResult.Cancel
Environment.Exit(0)
End Select
End If
Catch ex As Exception
' Something bad happened, but you don't know what exactly.
' You should exit, else it might keep happening
MsgBox("Your application encountered the following error and will now close: " _
& ex.Message)
Environment.Exit(0)
End Try
End While
' continue application
这篇关于在继续 VB.NET 之前等待特定程序打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!