如何在Go中处理Windows进程?

Tec*_*ger 9 windows go

我试图调用函数RegisterDeviceNotificationW的user32.dll.但是该函数的第一个参数是"将接收设备事件的窗口或服务的句柄"(这是我从微软获得的).

基于云打印机连接器我试图获取处理程序svc.StatusHandler(),但不适合我,每次运行时我得到以下错误:

句柄无效.

那么,使用相同的代码的例子中sys我创建了自己的"服务",取代了beep通过函数RegisterDeviceNotification(相同的代码谷歌),并派我的服务,并从返回的值的名字svc.StatusHandler(),但我又收到了同样的信息: "手柄无效."

函数RegisterDeviceNotification

var (
    u32                            = syscall.MustLoadDLL("user32.dll")
    registerDeviceNotificationProc = u32.MustFindProc("RegisterDeviceNotificationW")
)   
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

调用该函数

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)
}
Run Code Online (Sandbox Code Playgroud)

注意:我也尝试使用"myService"指针:

h := windows.Handle(uintptr(unsafe.Pointer(m)))
err := RegisterDeviceNotification(h)
Run Code Online (Sandbox Code Playgroud)

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

检索当前进程的伪句柄.

h, err := syscall.GetCurrentProcess()
err = RegisterDeviceNotification(windows.Handle(h))
Run Code Online (Sandbox Code Playgroud)

问题:如何在Go中获得有效的流程处理?

PS:如果我的问题存在任何问题,请告诉我改进.

sh.*_*seo 0

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)
}
Run Code Online (Sandbox Code Playgroud)