FindWindow函数的用法

时间:2025-03-31 20:05:03
 
Option Explicit
 
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long
 
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" ( _
    ByVal hWnd As Long, _
    ByVal wMsg As Long, _
    ByVal wParam As Long, lParam As Any) As Long
   
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" ( _
    ByVal hWnd As Long, _
    ByVal lpClassName As String, _
    ByVal nMaxCount As Long) As Long
   
Private Declare Function ShowWindow Lib "user32" ( _
    ByVal hWnd As Long, _
    ByVal nCmdShow As Long) As Long
   
Const SW_SHOWNORMAL = 1
Const WM_CLOSE = &H10
 
 
Public Sub test()
    Dim hWnd As Long
   
    ' 不知道类名
    hWnd = FindWindow(vbNullString, " 计算器 ")
    hWnd
End Sub
 
Public Sub test2()
    Dim hWnd As Long
   
    ' 知道计算器窗口的类名是 : SciCalc
    hWnd = FindWindow("SciCalc", vbNullString)
    hWnd
End Sub
 
Public Sub Test3()
 
    Dim hWnd As Long
    Dim lpClassName As String
    Dim retVal As Long
   
    hWnd = FindWindow(vbNullString, " 计算器 ")
    If hWnd = 0 Then MsgBox "Couldn't find the window ...": Exit Sub
   
    'Show the window
    ShowWindow hWnd, SW_SHOWNORMAL
   
    'Create a buffer
    lpClassName = Space(256)
   
    'retrieve the class name
    retVal = GetClassName(hWnd, lpClassName, 256)
   
    'Show the classname
    "Classname: " + Left(lpClassName, retVal)
   
    'Post a message to the window to close it
    PostMessage hWnd, WM_CLOSE, 0&, 0&
End Sub