Rubrik: Maus & Tastatur · Maus | VB-Versionen: VB5, VB6 | 26.03.08 |
Prüfen ob Maus über Form Eine Funktion, die prüft, ob sich der Mauszeiger aktuell innerhalb oder außerhalb der angegebenen Form befindet | ||
Autor: VBMichi | Bewertung: | Views: 10.632 |
www.michael-kaupp.com | System: Win9x, WinNT, Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Nachfolgender Code zeigt, wie sich prüfen lässt, ob sich die Maus aktuell innerhalb oder außerhalb einer angegebenen Form befindet.
Code für Modul:
Option Explicit ' benötigte API-Deklarationen Private Declare Function GetCursorPos Lib "user32" ( _ lpPoint As POINTAPI) As Long Private Type POINTAPI x As Long y As Long End Type Private Type FORMPOS Top As Long Bottom As Long Left As Long Right As Long End Type
' Form-Position unf Größe ermitteln und in FORMPOS-Struktur "merken" Private Function GetFormPos(lpPos As FORMPOS, Form As Form) As Long With Form lpPos.Left = .Left / Screen.TwipsPerPixelX lpPos.Top = .Top / Screen.TwipsPerPixelY lpPos.Right = (.Left + .Width) / Screen.TwipsPerPixelX lpPos.Bottom = (.Top + .Height) / Screen.TwipsPerPixelY End With End Function
' Prüft, ob sich die Maus innerhalb der Form befindet Private Function GetMousePos(curPos As POINTAPI, _ frmPos As FORMPOS) As Boolean With curPos GetMousePos = .x >= frmPos.Left And .x <= frmPos.Right _ And .y >= frmPos.Top And .y <= frmPos.Bottom End With End Function
' Gibt True zurück, wenn sich der Mauszeiger innerhalb ' der angegeben Form befindet, bzw. False, falls nicht Public Function IsMouseInForm(ByVal Form As Form) As Boolean Dim Result As Long Dim P As POINTAPI Dim F As FORMPOS ' aktuelle Mausposition Result = GetCursorPos(P) ' aktuelle Form-Größe und Position Result = GetFormPos(F, Form) ' Mausposition prüfen IsMouseInForm = GetMousePos(P, F) End Function
Nun können wir, als Beispiel, die Funktion in einem Timer (Timer1) alle 50 Millisekunden aufrufen und ihren Rückgabewert in einem Label (Label1) ausgeben:
Private Sub Form_Load() ' Timer initialisieren und starten Timer1.Interval = 50 Timer1.Enabled = True End Sub
Private Sub Timer1_Timer() ' Maus innerhalb/außerhalb der Form? If IsMouseInForm(Me) Then Label1.Caption = "STATUS:" & vbCrLf & _ "Maus befindet sich innerhalb der Form!" Else Label1.Caption = "STATUS:" & vbCrLf & _ "Maus befindet sich außerhalb der Form!" End If End Sub