getwindowrect和getcursorpos判断鼠标是否位于控件内部.frm

来自「GetWindowRect和GetCursorPos判断鼠标是否位于控件内部」· FRM 代码 · 共 82 行

FRM
82
字号
VERSION 5.00
Begin VB.Form Form1 
   Caption         =   "Form1"
   ClientHeight    =   3090
   ClientLeft      =   60
   ClientTop       =   450
   ClientWidth     =   7395
   LinkTopic       =   "Form1"
   ScaleHeight     =   206
   ScaleMode       =   3  'Pixel
   ScaleWidth      =   493
   StartUpPosition =   3  '窗口缺省
   Begin VB.TextBox Text1 
      Height          =   345
      Left            =   2160
      TabIndex        =   1
      Text            =   "Text1"
      Top             =   660
      Width           =   3825
   End
   Begin VB.CommandButton Command1 
      Caption         =   "Command1"
      Height          =   615
      Left            =   2250
      TabIndex        =   0
      Top             =   1380
      Width           =   2985
   End
   Begin VB.Timer Timer1 
      Interval        =   100
      Left            =   420
      Top             =   1740
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

'GetWindowRect和GetCursorPos两个API函数都是相对于屏幕坐标而言的
Private Declare Function GetWindowRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long

Private Type RECT
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
End Type

Private Type POINTAPI
    X As Long
    Y As Long
End Type

Dim lRect As RECT


Private Sub Timer1_Timer()
    Dim pnt As POINTAPI
    
    GetCursorPos pnt                           '获取鼠标指针的当前位置
    GetWindowRect Command1.hWnd, lRect         '获取控件的位置

    If pnt.X < lRect.Left Or _
       pnt.Y < lRect.Top Or _
       pnt.X > lRect.Right Or _
       pnt.Y > lRect.Bottom Then

        Text1.Text = "鼠标指针在Command1控件外"

    Else

        Text1.Text = "鼠标指针在Command1控件里"

    End If

End Sub

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?