在VB中运行批处理行

时间:2013-04-25 19:33:07

标签: c# vbscript batch-file

我正在努力自动化以前每晚运行的一些批处理文件。我目前已设置但由于它们最初是作为运行批处理文件的批处理文件编写的,因此我很难记录某些作业失败的时间和原因。我决定将这些作业重写为C#控制台应用程序或vbscript。这样做我遇到了一个大问题。

批处理文件包含以下行:

ctrbld warp7.p < y

ctrlbd.exe接受一个文件作为参数,warp7.p是文件,但需要按一下y才能启动。在该文件夹中是包含字符y的y文件。我是批处理文件的新手,无法弄清楚如何在vbscript或C#控制台应用程序中模拟此操作。它总是需要按键。

1 个答案:

答案 0 :(得分:1)

使用批处理管道,或使用 Sendkeys 方法将“ Y ”键发送到活动窗口(过程)。

批处理:

Echo Y|ctrbld.exe warp7.p

在使用批处理管道的VBS中

Set Shell = CreateObject("WScript.Shell")
Shell.RUN "CMD /k ""Echo Y|CMD.exe /k Process.exe"""

使用SendKeys的VBS:

Set Shell = CreateObject("WScript.Shell")
Shell.RUN "CMD.exe /K"
wscript.sleep(500) ' Wait 500 ms for CMD to fully load, change it if you need more time.
Shell.AppActivate "CMD"
Shell.SendKeys "Y"

在C#中使用批处理管道(可能语法错误'因为我在VB.Net上开发)

Process.start("CMD.exe", "/K ""Echo Y|CMD /K Process.exe""")

在C#中使用SendKeys (可能语法错误'因为我在VB.Net上开发)

Process.start("Process.exe")
Threading.thread.sleep(500) // Wait for process to load
AppActivate(Handle) // Activate the process window passing a Window Handle
SendKeys.Send("Y")

另外我还会给你一个额外的功能,我将在很久以前写过这个功能,你可以使用在线/离线代码翻译器将它翻译成C#,我的代码不需要激活Window来发送密钥(但只有密钥) ,而不是特殊的钥匙)。

  • 在使用Windows消息的VB.NET中

     #Region " SendKeys To App "
    
    ' [ SendKeys To App Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' SendKeys_To_App("notepad.exe", "By Elektro H@cker" & vbCrLf & "... :D")
    
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
    Private Const EM_REPLACESEL = &HC2
    
    Private Function SendKeys_To_App(ByVal App_Name As String, ByVal str As String) As Boolean
        Dim nPadHwnd As Long, ret As Long, EditHwnd As Long
        Dim APP_WindowTitle As String
    
        If App_Name.ToLower.EndsWith(".exe") Then App_Name = App_Name.Substring(0, App_Name.Length - 4) ' Rename APP Name
    
        Dim ProcessArray = Process.GetProcessesByName(App_Name)
        If ProcessArray.Length = 0 Then
            Return False ' App not found
        Else
            APP_WindowTitle = ProcessArray(0).MainWindowTitle ' Set window title of the APP
        End If
    
        nPadHwnd = FindWindow(App_Name, APP_WindowTitle)
    
        If nPadHwnd > 0 Then
            EditHwnd = FindWindowEx(nPadHwnd, 0&, "Edit", vbNullString) ' Find edit window
            If EditHwnd > 0 Then ret = SendMessage(EditHwnd, EM_REPLACESEL, 0&, str) ' Send text to edit window
            Return True  ' Text sended
        Else
            Return False ' Name/Title not found
        End If
    
    End Function
    
    #End Region