VB6检测 EXCEL是否运行,如果运行,则关闭所有EXCEL进程
DefeiSoft
编辑于 2023年03月22日 09:09

VB6检测 EXCEL是否运行,如果运行,则关闭所有EXCEL进程

代码块
JavaScript
自动换行
复制代码
'声明API函数
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, ByVal lParam As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
    (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" _
    (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" _
    (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
    ByVal dwProcessId As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" _
    (ByVal hProcess As Long, ByVal uExitCode As Long) As Long

'定义常量
Private Const WM_CLOSE = &H10
Private Const PROCESS_TERMINATE = &H1

Sub CloseAllExcelProcesses()
    Dim hWnd As Long '定义窗口句柄
    Dim procId As Long '定义进程ID
    Dim hProcess As Long '定义进程句柄
    Dim strText As String '定义窗口文本
    Dim iRet As Long '定义返回值
    
    '查找Excel的窗口句柄
    hWnd = FindWindow("XLMAIN", vbNullString)
    While hWnd <> 0
        '获取窗口文本
        strText = Space(256)
        GetWindowText hWnd, strText, Len(strText)
        strText = Left(strText, InStr(strText, vbNullChar) - 1)
        '如果窗口文本包含“Microsoft Excel”字符串,则表示该窗口属于Excel应用程序
        If InStr(1, strText, "Microsoft Excel") > 0 Then
            '获取窗口所属进程ID
            procId = 0
            GetWindowThreadProcessId hWnd, procId
            '打开进程句柄
            hProcess = OpenProcess(PROCESS_TERMINATE, 0, procId)
            '终止进程
            iRet = TerminateProcess(hProcess, 0)
            '关闭窗口
            iRet = PostMessage(hWnd, WM_CLOSE, 0, 0)
        End If
        '查找下一个Excel窗口
        hWnd = FindWindowEx(0, hWnd, "XLMAIN", vbNullString)
    Wend
End Sub
复制成功

上述代码使用Windows API函数FindWindow和FindWindowEx来查找Excel窗口句柄,然后使用GetWindowText函数获取窗口文本,判断窗口是否属于Excel应用程序。如果是,使用GetWindowThreadProcessId函数获取窗口所属进程ID,然后使用OpenProcess函数打开进程句柄,最后使用TerminateProcess函数终止进程并使用PostMessage函数发送关闭窗口消息。