从GOlang调用Windows SendMessageW永远不会返回



试图为Windows编写一个非常简单的关闭监视器的GO程序。代码如下:

//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)
}

该程序确实工作(IE>监视器关闭(,但从不从procSendMsg返回。调用((--没有错误,而且我从未看到"a"one_answers"b"的输出。我必须按Ctrl-C键才能退出这个程序。

很明显,我在调用user32.dll函数时出错了。。。这是我第一次尝试用GO编写Windows程序。

我做错了什么?

[仅供参考:我从这个PowerShell脚本中得到了这个想法:

(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)

]

感谢您的反馈!!

FYI:这是工作版本。

//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)
}
}

最新更新