Trying to write a very simple GO program for Windows that turns off the monitor. The code looks like this:
//go:build windows
// +build windows
package main
import (
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
)
func main() {
user32DLL := windows.NewLazyDLL("user32.dll")
procSendMsg := user32DLL.NewProc("SendMessageW")
a, b, err := procSendMsg.Call(0xFFFF, 0x0112, 0xF170, 2)
if err != nil {
log.Errorf("Error returned from SendMsg: %v", err)
}
log.Infof("a = %v, b = %v:", a, b)
}
The program does work (IE> the monitor turns off), but never returns from the procSendMsg.Call() -- no errors, and I never see the output of 'a' and 'b'. I have to Ctrl-C to get out of the program.
Obviously I'm doing something wrong w.r.t. calling the user32.dll function...this IS my first attempt at writing a Windows program with GO.
What am I doing wrong?
[FYI: I got the idea from this PowerShell script:
(Add-Type -MemberDefinition "[DllImport(""user32.dll"")]`npublic static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);" -Name "Win32SendMessage" -Namespace Win32Functions -PassThru)::SendMessage(0xffff, 0x0112, 0xF170, 2)
]
Thanks for your feedback!!
FYI: Here is the working version.
//go:build windows
// +build windows
package main
//
// turnOffMonitor -- Shuts down the signal to the monitor on Windows. A better power saver
// over using 'scrnsave.scr /s' to just blank the screen.
//
// John D. Allen
// September, 2022
//
import (
"strings"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
)
func main() {
user32DLL := windows.NewLazyDLL("user32.dll")
procPostMsg := user32DLL.NewProc("PostMessageW")
_, _, err := procPostMsg.Call(0xFFFF, 0x0112, 0xF170, 2)
//
// I get a "Access is denied." error when I run this from a user that does
// not have SYSTEM rights...but it still works anyway for some reason.
if err != nil && !strings.Contains(err.Error(), "Access is denied.") {
log.Errorf("Error returned from PostMsg(): %v", err)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.