在后台运行.bat

时间:2011-09-27 22:59:33

标签: vb.net visual-studio visual-studio-2010

所以我在编码中有这个:

vb代码:

file = My.Computer.FileSystem.OpenTextFileWriter("c:\command.bat", False)
        file.WriteLine("@echo off")
        file.WriteLine("cd " & TextBox2.Text)
        file.WriteLine("adb shell dumpsys meminfo " & TextBox1.Text & " > C:\Sample.txt")
        file.Close()
        Shell("C:\command.bat") 

我想要它做的是运行批处理文件而不打开它是否有意义。现在,它在一个循环上运行10分钟,每隔2秒打开一次,然后关闭.bat。看到.bat每两秒打开和关闭一次真的很烦人。反正有没有让这个过程在后台静默运行,所以用户甚至不知道它正在运行?

2 个答案:

答案 0 :(得分:3)

Shell("C:\command.bat", AppWinStyle.Hide)

这将运行批处理文件,但窗口是隐藏的。

或使用David建议的Process.Start。使用WindowStyle = ProcessWindowStyle.Hidden

答案 1 :(得分:3)

以下是如何将Process.Start与隐藏窗口一起使用的示例

    Dim params As String = "C:\command.bat"
    Dim myProcess As New ProcessStartInfo
    myProcess.FileName = "cmd.exe"
    myProcess.Arguments = params
    myProcess.WindowStyle = ProcessWindowStyle.Hidden
    Process.Start(myProcess)

如果您遇到路径中找不到文件错误的问题,您可以尝试添加以下Windows API调用并通过此函数运行文件路径。

'This would be declared at the top of your Form Code/Class Code
Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
ByVal lpszLongPath As String, _
ByVal lpszShortPath As StringBuilder, _
ByVal cchBuffer As Integer) As Integer

这是返回ShortPath的函数(win98样式路径(即c:/progra~1/myfolder/myfile.bat)

Public Function GetShortPath(ByVal longPath As String) As String
    Dim requiredSize As Integer = GetShortPathName(longPath, Nothing, 0)
    Dim buffer As New StringBuilder(requiredSize)

    GetShortPathName(longPath, buffer, buffer.Capacity)
    Return buffer.ToString()
End Function

然后在process.start函数

中简单地调用这样的路径
    Dim params As String = GetShortPathName("C:\command.bat")