简体   繁体   中英

Ruby: How to Get Screen Resolution in Windows

I saw one post back a while ago, but the main answer was for Linux. Currently, what's the easiest way to get the screen resolution (width/height) using Ruby on Windows.

One easy way is to wrap system commands and execute them in Ruby:

@screen = `wmic desktopmonitor get screenheight, screenwidth`

You can either display them or save its output in a file.

To actually parse it, I found a helper for Windows cmd.exe in this post :

for /f %%i in ('wmic desktopmonitor get screenheight^,screenwidth /value ^| find "="') do set "%%f"
echo your screen is %screenwidth% * %screenheight% pixels

This way you can easily get the values in variables and store them in your Ruby program.

I couldn't find a simple gem though to do this, as you have for Linux.

You might try this code as suggested on ruby-forum.com which uses the WIN32OLE library. This works for Windows exclusively, though.

 require 'dl/import' require 'dl/struct' SM_CXSCREEN = 0 SM_CYSCREEN = 1 user32 = DL.dlopen("user32") get_system_metrics = user32['GetSystemMetrics', 'ILI'] x, tmp = get_system_metrics.call(SM_CXSCREEN,0) y, tmp = get_system_metrics.call(SM_CYSCREEN,0) puts "#{x} x #{y}" 

I also suggest to go straight with system command wrapping. Tested on win7.

# also this way
res_cmd =  %x[wmic desktopmonitor get screenheight, screenwidth]
res = res_cmd.split
p w = res[3].to_i
p h = res[2].to_i

# or this way
command = open("|wmic desktopmonitor get screenheight, screenwidth")
res_cmd = command.read()
res = res_cmd.split
p w = res[3].to_i
p h = res[2].to_i

# or making a method
def screen_res
    res_cmd =  %x[wmic desktopmonitor get screenheight, screenwidth]
    res = res_cmd.split
    return res[3].to_i, res[2].to_i
end

w, h = screen_res

p w
p h

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM