計算機二級考試VisualBasic輔導:VB關(guān)閉已知標題窗口代碼

字號:

使用API函數(shù)。先通過FindWindow得到窗口的句柄,然后對窗口發(fā)送關(guān)閉消息。
    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
    Const WM_CLOSE = &H10  
     Private Sub Command1_Click()
    Dim hwnd, result As Long
    hwnd = FindWindow(vbNullString, "迅雷5") '查找窗體標題
    If hwnd = 0 Then
    MsgBox "未找到窗口"
    Else
    result = PostMessage(hwnd, WM_CLOSE, 0&, 0&)
    If result = 0 Then
    MsgBox "關(guān)閉窗口失敗"
    Else
    MsgBox "關(guān)閉OK"
    End If
    End If
    End Sub