- 1 year ago
windows-how to get screen resolution in golang
Comment
1 / 1
To get the screen resolution in Go on Windows, you can use the syscall
package to call the Windows API functions. Here's an example of how you can do it:
gopackage main
import (
"fmt"
"syscall"
"unsafe"
)
var user32 = syscall.NewLazyDLL("user32.dll")
var getSystemMetrics = user32.NewProc("GetSystemMetrics")
var getDC = user32.NewProc("GetDC")
var getDeviceCaps = user32.NewProc("GetDeviceCaps")
var releaseDC = user32.NewProc("ReleaseDC")
const (
SM_CXSCREEN = 0
SM_CYSCREEN = 1
)
const (
LOGPIXELSX = 88
LOGPIXELSY = 90
)
func getScreenResolution() (int, int) {
width := getSystemMetrics.Call(SM_CXSCREEN)
height := getSystemMetrics.Call(SM_CYSCREEN)
return int(width), int(height)
}
func getDPI() (int, int) {
hdc, _, _ := getDC.Call(0)
defer releaseDC.Call(hdc)
xDPI, _, _ := getDeviceCaps.Call(hdc, LOGPIXELSX)
yDPI, _, _ := getDeviceCaps.Call(hdc, LOGPIXELSY)
return int(xDPI), int(yDPI)
}
func main() {
screenWidth, screenHeight := getScreenResolution()
xDPI, yDPI := getDPI()
fmt.Printf("Screen Resolution: %dx%d\n", screenWidth, screenHeight)
fmt.Printf("DPI: %dx%d\n", xDPI, yDPI)
}
This code uses the Windows API functions GetSystemMetrics
to retrieve the screen width and height and GetDeviceCaps
to retrieve the DPI. The syscall
package is used to make these API calls.
Please note that this example might need administrative privileges to access certain system resources. Make sure to run it as an administrator or adjust the security settings accordingly.