微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB6: 通过窗口句柄得到窗口所在程序的名称和路径(实例)

Option Explicit

Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String,ByVal lpWindowName As String) As Long
Public Declare Function GetwindowThreadProcessId Lib "user32" (ByVal hwnd As Long,lpdwProcessId As Long) As Long
Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long,ByVal bInheritHandle As Long,ByVal dwProcId As Long) As Long
Public Declare Function EnumProcessModules Lib "psapi.dll" (ByVal hProcess As Long,ByRef lphModule As Long,ByVal cb As Long,ByRef cbNeeded As Long) As Long
Public Declare Function GetmodulefileNameEx Lib "psapi.dll" Alias "GetmodulefileNameExA" (ByVal hProcess As Long,ByVal hModule As Long,ByVal ModuleName As String,ByVal nSize As Long) As Long
Public Const PROCESS_QUERY_informatION = &H400
Public Const PROCESS_VM_READ = &H10

Sub main()
    If FindWindow(vbNullString,"计算器") = 0 Then
        Shell "calc.exe"
    End If
    Debug.Print GetmodulefileNameByHwnd(FindWindow(vbNullString,"计算器"))
End Sub

'<>
'********************************************************************************
' 函数: GetmodulefileNameByHwnd
' 功能: 通过窗口句柄得到模块名称
'********************************************************************************
'<>
Public Function GetmodulefileNameByHwnd(ByVal hWindow As Long) As String

    Dim dwProcId        As Long
    Dim hProcess        As Long
    Dim hModule         As Long
    Dim nRet            As Long
    Dim szBuf           As String
    Const MAX_SIZE      As Long = 256
    
    If hWindow <= 0 Then Exit Function
    
    '' 得到进程ID
    Call GetwindowThreadProcessId(hWindow,dwProcId)
    If dwProcId = 0 Then Exit Function
    
    '' 根据进程ID,取得进程的句柄
    hProcess = OpenProcess(PROCESS_QUERY_informatION Or PROCESS_VM_READ,dwProcId)
    If hProcess = 0 Then Exit Function
    
    '' 枚举进程中的各个模块
    nRet = EnumProcessModules(hProcess,hModule,4&,0&)
    If nRet = 0 Then Exit Function
    
    '' 最后用下面这个函数得到可执行文件名称
    szBuf = String$(MAX_SIZE,vbNullChar)
    GetmodulefileNameEx hProcess,szBuf,Len(szBuf)
    GetmodulefileNameByHwnd = StripNulls(szBuf)
    
End Function

'
'-----------------------------------------------------------------------------
'
'***********************************************************
' 函数: StripNulls
' 功能: 清除字符串中多余的Null
'***********************************************************
Public Function StripNulls(ByRef szOriginal As String) As String
Dim i As Long
    i = InStr(szOriginal,vbNullChar)
    If i > 0 Then
        szOriginal = Left$(szOriginal,i - 1)
    End If
    StripNulls = szOriginal
End Function

参考: 怎样由窗口句柄得到窗口所在程序的名称和路径

原文地址:https://www.jb51.cc/vb/259484.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐