我正在自动化一些以前每晚运行的批处理文件。我具有当前设置,但是由于它们最初是作为运行批处理文件的批处理文件编写的,因此我很难记录何时以及为什么某些作业失败。我决定将这些作业重写为C#控制台应用程序或vbscript。在执行此操作时,我遇到了一个大问题。
批处理文件具有以下行:
ctrbld warp7.p < y
ctrlbd.exe将文件warp7.p作为文件接受参数,但是需要按y键才能启动。文件夹中是一个包含字符y的y文件。我是批处理文件的新手,无法弄清楚如何在vbscript或C#控制台应用程序中模拟此操作。它始终仍然需要按键。
最佳答案
使用批处理管道,或使用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
关于c# - 在VB中运行批生产线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16223250/