HOME > 即効テクニック > Excel VBA > その他関連のテクニック > マウスの位置からクラス名を取得する

即効テクニック

その他関連のテクニック

マウスの位置からクラス名を取得する

(Excel 97/2000)
サンプルマクロは、マウスポインタの位置から親ウインドのクラス名を取得します。
Option Explicit

Private Type POINTAPI
    x As Long
    y As Long
End Type

Declare Function GetCursorPos Lib "User32" _
    (lpPoint As POINTAPI) As Long
Declare Function WindowFromPointXY Lib "User32" _
    Alias "WindowFromPoint" _
    (ByVal xPoint As Long, ByVal yPoint As Long) As Long
Declare Function GetParent Lib "User32" _
    (ByVal hwnd As Long) As Long
Declare Function GetClassName Lib "User32" Alias "GetClassNameA" _
    (ByVal hwnd As Long, ByVal lpClassName As String, _
    ByVal nMaxCount As Long) As Long

Sub Sample()

    Dim myMousePt As POINTAPI
    Dim myX As Long, myY As Long
    Dim myPointhwnd As Long, myParenthwnd As Long
    Dim myParentClassName As String * 100
    
    Call GetCursorPos(myMousePt)
        With myMousePt
            myX = .x
            myY = .y
        End With
    myPointhwnd = WindowFromPointXY(myX, myY)
    myParenthwnd = GetParent(myPointhwnd)
    If myParenthwnd <> 0 Then
        Call GetClassName(myParenthwnd, myParentClassName, 100)
        MsgBox Left(myParentClassName, _
            InStr(myParentClassName, vbNullChar) - 1)
            '95ではvbNullCharに替えてChr(0)を使用
    End If

End Sub