gpt4 book ai didi

windows - 如何在 Go 中获取 Windows 进程的句柄?

转载 作者:IT王子 更新时间:2023-10-29 01:06:17 26 4
gpt4 key购买 nike

我正在尝试调用 user32.dll 的函数 RegisterDeviceNotificationW。但是该函数的第一个参数是“将接收设备事件的窗口或服务的句柄”(这是我从 Microsoft 获得的)。

基于 Cloud Printer Connector我尝试使用 svc.StatusHandler() 获取处理程序,但对我不起作用,每次运行时都会出现以下错误:

The handle is invalid.

嗯,使用与 examples 相同的代码sys 我创建了自己的“服务”,将 beep 函数替换为 RegisterDeviceNotification(与 google 相同的代码)并发送了名称我的服务和从 svc.StatusHandler() 返回的值,但我再次收到相同的消息:“句柄无效。”

函数注册设备通知

var (
u32 = syscall.MustLoadDLL("user32.dll")
registerDeviceNotificationProc = u32.MustFindProc("RegisterDeviceNotificationW")
)

这是我需要发送有效处理程序的地方

func RegisterDeviceNotification(handle windows.Handle) error {

var notificationFilter DevBroadcastDevinterface
notificationFilter.dwSize = uint32(unsafe.Sizeof(notificationFilter))
notificationFilter.dwDeviceType = DBT_DEVTYP_DEVICEINTERFACE
notificationFilter.dwReserved = 0
// BUG(pastarmovj): This class is ignored for now. Figure out what the right GUID is.
notificationFilter.classGuid = PRINTERS_DEVICE_CLASS
notificationFilter.szName = 0

r1, _, err := registerDeviceNotificationProc.Call(uintptr(handle), uintptr(unsafe.Pointer(&notificationFilter)), DEVICE_NOTIFY_SERVICE_HANDLE|DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)
if r1 == 0 {
return err
}
return nil
}

调用函数

func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
h := windows.Handle(uintptr(unsafe.Pointer(m)))
err := RegisterDeviceNotification(h)

fmt.Println(err)
}

注意:我也尝试使用“myService”的指针:

h := windows.Handle(uintptr(unsafe.Pointer(m)))
err := RegisterDeviceNotification(h)

编辑: 我试过 GetCurrentProcess , 但不起作用:

Retrieves a pseudo handle for the current process.

h, err := syscall.GetCurrentProcess()
err = RegisterDeviceNotification(windows.Handle(h))

问题:如何在 Go 中获取进程的有效句柄?

PS:如果我的问题有任何问题,请告诉我以改进。

最佳答案

syscall.GetCurrentProcess()可以这样使用。

package main

import (
"fmt"
"syscall"
"unsafe"
)

func main() {
kernel32, err := syscall.LoadDLL("kernel32.dll")
if err != nil {
fmt.Println(err)
}
defer kernel32.Release()

proc, err := kernel32.FindProc("IsWow64Process")
if err != nil {
fmt.Println(err)
}

handle, err := syscall.GetCurrentProcess()
if err != nil {
fmt.Println(err)
}

var result bool

_, _, msg := proc.Call(uintptr(handle), uintptr(unsafe.Pointer(&result)))

fmt.Printf("%v\n", msg)
}

关于windows - 如何在 Go 中获取 Windows 进程的句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com