|
请教VB.NET区域找到图片就点击,没找到等待15秒后再找
点 Button1后,如果匹配模板出现的屏幕上,鼠标就进行移动点击,如果匹配模板没有出现,就等待它出现,如果15秒没有出现,就重新继续等待,直到匹配模板出现或者程序中继。下面的代码匹配模板不管出不出现,15秒后鼠标都进行点击了,请大神们看看哪里出问题了。
完整的代码在附件
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim templatePath As String = "C:\报表查询.jpg"
Dim isMatched As Boolean = False
While Not isMatched
Try
AppendTextToTextBox($"开始新的一轮模板匹配尝试,当前时间:{DateTime.Now}")
Dim screenCapture As Bitmap = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb)
Using g As Graphics = Graphics.FromImage(screenCapture)
g.CopyFromScreen(0, 0, 0, 0, New Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
End Using
screenCapture = ConvertTo24BitBitmap(screenCapture)
matches.Clear()
matches(templatePath) = ProcessTemplateMatch(screenCapture, templates(templatePath))
If matches(templatePath).Length > 0 Then
isMatched = True
Dim firstMatch As TemplateMatch = matches(templatePath)(0)
Dim x As Integer = firstMatch.Rectangle.Location.X + firstMatch.Rectangle.Width \ 2
Dim y As Integer = firstMatch.Rectangle.Location.Y + firstMatch.Rectangle.Height \ 2
' 将屏幕坐标转换为绝对坐标
x = (x * 65535) \ Screen.PrimaryScreen.Bounds.Width
y = (y * 65535) \ Screen.PrimaryScreen.Bounds.Height
' 移动鼠标到匹配位置
SendInput(1, New INPUT() {New INPUT With {.type = 0, .ki = New MOUSEINPUT With {.dx = x, .dy = y, .dwFlags = MOUSEEVENTF_ABSOLUTE Or MOUSEEVENTF_MOVE}}}, Marshal.SizeOf(GetType(INPUT)))
' 执行点击操作
SendInput(1, New INPUT() {New INPUT With {.type = 0, .ki = New MOUSEINPUT With {.dwFlags = MOUSEEVENTF_LEFTDOWN}}}, Marshal.SizeOf(GetType(INPUT)))
SendInput(1, New INPUT() {New INPUT With {.type = 0, .ki = New MOUSEINPUT With {.dwFlags = MOUSEEVENTF_LEFTUP}}}, Marshal.SizeOf(GetType(INPUT)))
AppendTextToTextBox($"成功匹配到模板并执行了点击操作,当前时间:{DateTime.Now}")
Else
' 如果未匹配到模板,等待15秒后再次尝试
AppendTextToTextBox($"本轮模板匹配尝试结束,未匹配到模板,等待15秒后将再次尝试,当前时间:{DateTime.Now}")
System.Threading.Thread.Sleep(15000)
End If
Catch ex As Exception
AppendTextToTextBox($"在模板匹配过程中发生异常:{ex.Message}")
End Try
End While
End Sub
|
|