VB 通过进程PID获取该程序的窗口句柄函数

本文介绍了一种通过进程ID获取其窗口句柄的方法,使用了API函数如FindWindow、GetWindowThreadProcessId等,实现了从顶级窗口遍历并匹配目标进程的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Option Explicit
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal Hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetParent Lib "user32" (ByVal Hwnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal Hwnd As Long, ByVal wCmd As Long) As Long
Const GW_HWNDNEXT = 2
' 通过进程ID获得该进程的窗口句柄
Public Function InstanceToWnd(ByVal target_pid As Long) As Long
    Dim test_hwnd As Long
    Dim test_pid As Long
    Dim test_thread_id As Long
    InstanceToWnd = 0
    'On Error Resume Next
    ' 获得首个handle.
    test_hwnd = FindWindow(ByVal 0&, ByVal 0&)

    ' 循环查找直到找到为给定进程ID的窗口句柄
    Do While test_hwnd <> 0
        '检查窗口句柄是否为顶级窗口
        If GetParent(test_hwnd) = 0 Then
            ' 是顶级窗口
            ' 取该窗口所属的进程ID
            test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)

            If test_pid = target_pid Then
                ' 是我们指定进程的窗口,则将该窗口的句柄返回到函数名,并退出
                InstanceToWnd = test_hwnd
                Exit Do
            End If
        End If

        ' 取下一个窗口的句柄
        test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
    Loop
End Function
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值