登录
首页 >  Golang >  Go问答

GetWindowThreadProcessId 返回的进程 ID 与 TaskManager 中的进程 ID 不一致

来源:stackoverflow

时间:2024-02-19 10:30:27 230浏览 收藏

大家好,今天本人给大家带来文章《GetWindowThreadProcessId 返回的进程 ID 与 TaskManager 中的进程 ID 不一致》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在尝试使用 go 获取 windows 10 上活动前台窗口的 pid。

首先我调用这个函数并获取句柄:

func getforegroundwindow() uintptr {
    us32 := syscall.mustloaddll("user32.dll")
    prc := us32.mustfindproc("getforegroundwindow")
    ret, _, _ := prc.call()
    return ret
}

稍后使用从上面函数返回的句柄,我将调用此函数:

func getwindowthreadprocessid(hwnd uintptr) uintptr {
    us32 := syscall.mustloaddll("user32.dll")
    prc := us32.mustfindproc("getwindowthreadprocessid")
    ret, _, err := prc.call(hwnd, uintptr(unsafe.pointer(&hwnd)))
    fmt.println("processid: ", ret, " error: ", err)
    return ret
}

当我通过运行 tasklist /fi "pid eq returnedpid" 交叉检查返回的 pid 时,它与任何进程都不匹配。

对 openprocess 的调用始终返回 0,并显示错误“参数不正确”。

func GetOpenProcess(pid uintptr) {
    kernel32 := syscall.MustLoadDLL("kernel32.dll")
    proc := kernel32.MustFindProc("OpenProcess")
    res, _, err := proc.Call(ptr(PROCESS_ALL_ACCESS|PROCESS_QUERY_INFO), ptr(true), ptr(pid))
    fmt.Println("OpenProcess: result:", res, " Error:", err)
}

我做错了什么?


解决方案


我能够根据 https://stackoverflow.com/users/1889329/iinspectable 的评论解决该问题

我做错的是,尝试使用从系统调用返回的值,并且将指向窗口句柄的指针作为第二个参数传递给 getwindowthreadprocessid() 函数,这也是错误的。相反,要获取活动窗口进程 id,我必须传递一个新指针(第二个参数),并在函数返回后使用该指针的值而不是返回值。因为,getwindowthreadprocessid函数将pid写入第二个参数指向的位置。

请在下面找到修改后的代码:

func GetWindowThreadProcessId(hwnd uintptr) uintptr {
    var prcsId uintptr = 0
    us32 := syscall.MustLoadDLL("user32.dll")
    prc := us32.MustFindProc("GetWindowThreadProcessId")
    ret, _, err := prc.Call(hwnd, uintptr(unsafe.Pointer(&prcsId)))
    log.Println("ProcessId: ", prcsId, "ret", ret, " Message: ", err)
    return prcsId
}

函数日志: 2020/04/18 14:31:21 processid: 13652 ret 13644 消息:操作成功完成。

今天关于《GetWindowThreadProcessId 返回的进程 ID 与 TaskManager 中的进程 ID 不一致》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>