2

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

批处理文件有这一行:

ctrbld warp7.p < y

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

4

1 回答 1

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#,我的代码不需要激活窗口来发送密钥(但只有密钥,不是特殊的键)。

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

     #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
    
于 2013-04-25T19:51:41.160 回答