我必须使用VB.Net
自动执行Windows应用程序(无API)的重复性任务。
我所做的是模拟通常由用户完成的击键。
我正在使用System.Threading
,并使用新流程启动应用程序。
我的问题是,当任务完成时,此应用程序弹出一个消息框,此消息框确定禁用主应用程序窗口,因此我需要知道何时显示此消息框以模拟 ENTER < / kbd>击键并继续下一个任务。
以下是我的代码示例:
Imports System.Threading
Public Class Form1
Dim a As New Process
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
a.StartInfo.FileName = "C:\Program Files (x86)\CE\CE.exe"
a.Start()
AppActivate(a.Id)
For i = 1 To CInt(txt.Text)
DoTask()
Next
End Sub
Private Sub DoTask()
Thread.Sleep(1000)
SendKeys.SendWait("^(N)")
Thread.Sleep(500)
SendKeys.SendWait("{ENTER}")
Thread.Sleep(500)
SendKeys.SendWait("new check")
Thread.Sleep(500)
SendKeys.SendWait("{ENTER}")
Do While True
'Here I want to wait until a message box pops up by the application
'If message box displayed then exit do
Loop
SendKeys.SendWait("{ENTER}")
End Sub
End Class
请帮我解决这个问题。 谢谢
答案 0 :(得分:2)
我个人使用AutoIt来完成这类任务 - 有一个WinWaitActive函数,它等待一个具有指定标题或类名的窗口打开并激活,然后你只需向它发送按键。
请参阅https://www.autoitscript.com/autoit3/docs/functions/WinWaitActive.htm
在VB中,我认为您必须执行以下操作:等待具有指定标题或类名的窗口变为可见并激活。
Determine Whether Program is the Active Window in .NET
如果你需要坚持使用VB,你可以导入并使用AutoIt DLL:
Running AutoIt3 Scripts in VB 2010
AutoIt编辑器中有一个很好的工具,可以让你检查窗口及其子控件,并在脚本中使用类名。例如,我编写了代码,等待直到ALV网格与结果集显示在SAP窗口中:
Func _WaitForALVGrid()
Sleep(5000)
_WinWaitActivate($windowName,"")
Local $count = 0
Do
Sleep(5000)
$count = $count + 1
$Text=ControlGetText("[CLASS:SAP_FRONTEND_SESSION]","","[CLASS:Afx:63DE0000:8:00010003:00000010:00000000]")
if StringLeft($Text, 6) = "Nebyla" Then Return False
if $count>360 Then Return False
Until StringInStr(WinGetClassList($windowName), "SapALVGrid")>0
_WinWaitActivate($windowName,"")
Sleep(5000)
Return True
EndFunc
VB.NET中还有一种不使用AutoIT的方法 - 类似于WinWaitActivate:
http://forums.codeguru.com/showthread.php?460402-C-General-How-do-I-activate-an-external-Window
Class Program
<DllImportAttribute("User32.dll")> _
Private Shared Function FindWindow(ClassName As [String], WindowName As [String]) As Integer
End Function
<DllImportAttribute("User32.dll")> _
Private Shared Function SetForegroundWindow(hWnd As Integer) As IntPtr
End Function
Private Shared Sub Main(args As String())
'**************************** CODE YOU SEEK?
'Find the window, using the CORRECT Window Title, for example, Notepad
Dim hWnd As Integer = 0
While hWnd = 0
Thread.Sleep(1000)
hWnd = FindWindow(Nothing, "Untitled - Notepad")
End While
'If found activate it
SetForegroundWindow(hWnd)
'**************************** CODE YOU SEEK?
End Sub
End Class
另一个很好的例子是: