Using Golang to start Windows downtime (GetLastInputInfo or similar)

Is there an example or method for getting Windows system down with Go?
I looked at the documentation on the Golang website, but I think that I do not have enough access (and use) of the API to get system information, including downtime.

+7
winapi go
source share
1 answer
Web site

Go is hard-coded to display documentation for standard library packages on Linux. You will need to get godoc and run it yourself:

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

then open http://127.0.0.1:6060/ in your web browser.

Of note is the syscall package, which provides options for accessing functions in a DLL, including UTF-16 helpers and callback generation functions.

Performing a quick recursive search of the Go tree suggests that it does not have an API for GetLastInputInfo() in particular, so if I am missing something, you should be able to directly call this function from the 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()) } 

In your case structure is used. As far as I know, you can simply recreate the structure (keeping the fields in the same order), but you must convert any int fields in the original to int32 , otherwise things will be split into 64-bit Windows . See the Windows Data Types page on MSDN for the corresponding type equivalents. In your case it will be

 var lastInputInfo struct { cbSize uint32 dwTime uint32 } 

Since this (like many structures in the Windows API) has a cbSize field that requires you to initialize it with the size of the structure, we must also do this:

 lastInputInfo.cbSize = uint32(unsafe.Sizeof(lastInputInfo)) 

Now we just need to pass lastInputInfo to the function pointer to this variable:

 r1, _, err := getLastInputInfo.Call( uintptr(unsafe.Pointer(&lastInputInfo))) 

and just remember to import syscall and unsafe .

All DLL/LazyDLL.Call() arguments are uintptr , as is r1 return. Return _ never used on Windows (it is related to the ABI used).


Since I reviewed most of what you need to know in order to use the Windows API in Go, which you cannot extract from reading syscall documents, I will also say (and this is not relevant to the above question) that if the function has both ANSI versions , and Unicode, for best results you should use Unicode versions (suffix W ) and the UTF-16 conversion functions in the syscall package.

I think that all the information that you (or any other, for that matter) will need to use the Windows API in Go programs.

+21
source share

All Articles