Home >Backend Development >Golang >How to Retrieve Windows Idle Time Using Go?

How to Retrieve Windows Idle Time Using Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 13:45:02935browse

How to Retrieve Windows Idle Time Using Go?

Accessing Windows Idle Time with Go

This guide provides a solution to retrieving the idle time of a Windows system using Golang.

Accessing Windows API in Go

Getting Windows-specific system information requires using the syscall package. To access the API, you will need to obtain godoc and run it locally:

go get golang.org/x/tools/cmd/godoc
godoc --http=:6060

Then, open http://127.0.0.1:6060/ in a web browser.

Getting Last Input Info

Go does not have a direct API for GetLastInputInfo(). However, you can call it directly from the DLL:

<code class="go">user32 := syscall.MustLoadDLL("user32.dll")
getLastInputInfo := user32.MustFindProc("GetLastInputInfo")</code>

Setting Up a Structure

Define a structure to hold the return value:

<code class="go">type LastInputInfo struct {
    cbSize uint32
    dwTime  uint32
}</code>

Initialize the cbSize field with the size of the structure:

<code class="go">var lastInputInfo LastInputInfo
lastInputInfo.cbSize = uint32(unsafe.Sizeof(lastInputInfo))</code>

Calling GetLastInputInfo

Pass a pointer to the structure to the function:

<code class="go">_, _, err := getLastInputInfo.Call(
    uintptr(unsafe.Pointer(&lastInputInfo))))
if err != nil {
    panic("error getting last input info: " + err.Error())
}</code>

Remember to import syscall and unsafe.

Additional Tips

  • Use Unicode versions of API functions (e.g., W suffix) and UTF-16 conversion functions in syscall for optimal results.
  • All arguments and return values for syscall.Call() are uintptr.
  • The underscore (_) return is not used on Windows.

The above is the detailed content of How to Retrieve Windows Idle Time Using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn