Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

windows-how to get screen resolution in golang

Great guy.

I have a requirement to get the windows system screen resolution,but I can't get any useful thing about this with google.

So I look for help in stackoverflow.

Anyone know how to do it?

Thanks advance.

updates: then I try this commandwmic desktopmonitor get screenheight screenwidth and get the answer like this:
this is the cmd: enter image description here

this is go-program: enter image description here

like image 858
alphayan Avatar asked Nov 13 '17 02:11

alphayan


2 Answers

A bit late, but as suggested by Marco, you can use the Windows API GetSystemMetrics for this. The easiest way to do so is through the github.com/lxn/win package:

package main

import (
    "fmt"

    "github.com/lxn/win"
)

func main() {
    width := int(win.GetSystemMetrics(win.SM_CXSCREEN))
    height := int(win.GetSystemMetrics(win.SM_CYSCREEN))
    fmt.Printf("%dx%d\n", width, height)
}

Slightly more elaborate, using GetDeviceCaps:

package main

import (
    "fmt"

    "github.com/lxn/win"
)

func main() {
    hDC := win.GetDC(0)
    defer win.ReleaseDC(0, hDC)
    width := int(win.GetDeviceCaps(hDC, win.HORZRES))
    height := int(win.GetDeviceCaps(hDC, win.VERTRES))
    fmt.Printf("%dx%d\n", width, height)
}
like image 56
fstanis Avatar answered Sep 18 '22 13:09

fstanis


We can get screen resolution through powershell, and its are arguments are its scripts. so, I have included script in args variable.

Output is not straight forward, you will get someother extra information, try using bytes package or strings package to scan required information.

Following powershell command is retrived from here:

Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    args := "Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Screen]::AllScreens"
    out, err := exec.Command("powershell", args).Output()
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Print(string(out))
}

I have checked it in Windows 7 Virtual box, its working. You can run this from Command Prompt or powershell, as this calls powershell any how.

like image 33
nilsocket Avatar answered Sep 19 '22 13:09

nilsocket