使用Golang获取Windows空闲时间(GetLastInputInfo或类似)

Bar*_*rim 9 winapi go idle-timer

是否有使用Go获取Windows系统空闲时间的示例或方法?
我一直在看Golang网站上的文档,但我想我错过了如何访问(和使用)API来获取系统信息,包括空闲时间.

and*_*abs 24

Go的网站是硬编码的,以显示Linux上标准库包的文档.你需要得到godoc并自己运行:

go get golang.org/x/tools/cmd/godoc
godoc --http=:6060
Run Code Online (Sandbox Code Playgroud)

然后http://127.0.0.1:6060/在您的Web浏览器中打开.

值得注意的是package syscall,它提供了访问DLL中函数的工具,包括UTF-16帮助程序和回调生成函数.

对Go树进行快速递归搜索说它没有GetLastInputInfo()特别的API ,所以除非我遗漏了什么,你应该能够直接从DLL中调用该函数:

user32 := syscall.MustLoadDLL("user32.dll") // or NewLazyDLL() to defer loading
getLastInputInfo := user32.MustFindProc("GetLastInputInfo") // or NewProc() if you used NewLazyDLL()
// or you can handle the errors in the above if you want to provide some alternative
r1, _, err := getLastInputInfo.Call(uintptr(arg))
// err will always be non-nil; you need to check r1 (the return value)
if r1 == 0 { // in this case
    panic("error getting last input info: " + err.Error())
}
Run Code Online (Sandbox Code Playgroud)

你的案子涉及一个结构.据我所知,你可以重新创建结构平面(保持字段顺序相同),但你必须int原始字段中的任何字段转换为int32,否则在64位Windows上会出现问题.请参阅MSDN上Windows数据类型页面以获取相应的类型.在你的情况下,这将是

var lastInputInfo struct {
    cbSize uint32
    dwTime uint32
}
Run Code Online (Sandbox Code Playgroud)

因为这(与Windows API中的许多结构一样)有一个cbSize字段,要求您使用结构的大小初始化它,我们也必须这样做:

lastInputInfo.cbSize = uint32(unsafe.Sizeof(lastInputInfo))
Run Code Online (Sandbox Code Playgroud)

现在我们只需要将指向该lastInputInfo变量的指针传递给函数:

r1, _, err := getLastInputInfo.Call(
    uintptr(unsafe.Pointer(&lastInputInfo)))
Run Code Online (Sandbox Code Playgroud)

并且只记得导入syscallunsafe.

所有的参数传递给DLL/LazyDLL.Call()uintptr,因为是r1回报.该_回报是永远不会在Windows上使用(它做的ABI使用).


由于我查阅了你需要知道的大部分内容,你无法通过阅读syscall文档来收集Go中的Windows API ,我还会说(如果上面的问题无关),如果一个函数同时具有ANSI和Unicode版本,您应该W在包中使用Unicode版本(后缀)和UTF-16转换函数以syscall获得最佳结果.

我认为你所有的信息(或者任何人)都需要在Go程序中使用Windows API.