0

我有一个程序可以随机设置 x,y 坐标然后单击的光标。我有这个函数/子,它根据某些参数创建一个矩形。

Private Sub drawTitleBarRectangle()

    Dim titleBarRectangle As Rectangle = RectangleToScreen(Me.ClientRectangle)
    Dim titleBarRectangleHeight As Integer = titleBarRectangle.Top - Me.Top
    Dim titleBarRectangleWidth As Integer = Screen.PrimaryScreen.Bounds.Width
    Dim titleBarRectangleTop As Integer = Screen.PrimaryScreen.Bounds.Top

    Dim titleBarBounds As New Drawing.Rectangle(0, 0, titleBarRectangleWidth, titleBarRectangleHeight)
End Sub

我想检查光标何时位于 x,y 位置,是否在从该函数创建的矩形的边界内。现在我有这个:

       drawTitleBarRectangle()
            SetCursorPos(x, y)
            If titleBarRectangle.Contains(x, y) Then
                leftClick(800, 800)
            End If

Private titleBarRectangle是来自我声明的一个全局变量,因为Private titleBarRectangle As New Drawing.Rectangle我不太清楚为什么它在那里老实说......

任何帮助,将不胜感激。

4

1 回答 1

1

您列出的初始方法中的所有变量都是局部变量。这意味着当该方法退出时它们被简单地丢弃。您需要通过赋值而不是声明来更新已声明的类级别变量。考虑到这一点,它应该看起来更像:

Public Class Form1

    Private titleBarRectangle As Rectangle

    Private Sub drawTitleBarRectangle()
        Dim rc As Rectangle = Me.RectangleToScreen(Me.ClientRectangle)
        Dim titleBarRectangleHeight As Integer = rc.Top - Me.Top
        titleBarRectangle = New Rectangle(Me.Location.X, Me.Location.Y, Me.Width, titleBarRectangleHeight)
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        drawTitleBarRectangle()
        Debug.Print(titleBarRectangle.ToString)
        ControlPaint.DrawReversibleFrame(titleBarRectangle, Color.Black, FrameStyle.Dashed)

        Dim x As Integer = titleBarRectangle.Location.X + titleBarRectangle.Width / 2
        Dim y As Integer = titleBarRectangle.Location.Y + titleBarRectangle.Height / 2
        Cursor.Position = New Point(x, y)
        If titleBarRectangle.Contains(Cursor.Position) Then
            Debug.Print("It's in there!")
        End If
    End Sub

End Class

请注意方法中的最后一行将如何使用类级别变量而不是本地变量,因为我们Dim前面没有。

于 2013-11-13T17:38:26.633 回答