根据标题文本找到窗体句柄,然后发送关闭消息
以下代码放在一个标准模块中,enumwindows可以枚举窗口列表中的所有父窗口(顶级和被所有窗口),getwindowtext可以获得窗口标题,sendmessage发送WM_CLOSE消息到你要关闭的窗体就可以了
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Boolean
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Const WM_CLOSE = &H10
'这个函数是enumwindows回调用的,在这里加入处理代码就行
Public Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
Dim sSave As String, Ret As Long
Ret = GetWindowTextLength(hwnd)
sSave = Space(Ret)
GetWindowText hwnd, sSave, Ret + 1
Form1.Print Str $(hwnd) + " " + sSave '这行代码在窗体上显示所有窗口句柄和标题,把这行代码换成在标题中查找要限制的文本,如果找到就向这个窗口SendMessage hwnd, WM_CLOSE, 0, 0就可以了
EnumWindowsProc = True
End Function
以下为窗体模块中调用的代码,放在时间事件中,例如每4秒中检查一次窗口标题中是否包含限制文本
EnumWindows AddressOf EnumWindowsProc, ByVal 0&
知道标题是不行的,只有知道窗口的进程的PID或映象名称才能用VB自动把这个窗口关闭。