Ruby:如何在Windows中获取屏幕分辨率

5

我之前看到过一篇帖子,但主要回答是针对Linux的。目前,在Windows上使用Ruby获取屏幕分辨率(宽度/高度)的最简单方法是什么?


2
你尝试过这个答案吗? - Eric M. Johnson
3个回答

1
一种简单的方法是将系统命令封装起来,并在Ruby中执行它们:
@screen = `wmic desktopmonitor get screenheight, screenwidth`

你可以将它们显示出来,也可以将其输出保存在文件中。
要实际解析它,我在这篇文章中发现了一个Windows cmd.exe的助手。
for /f %%i in ('wmic desktopmonitor get screenheight^,screenwidth /value ^| find "="') do set "%%f"
echo your screen is %screenwidth% * %screenheight% pixels

这样,您就可以轻松地将值存储在变量中并在Ruby程序中使用。但是,我找不到一个像Linux那样简单的gem来完成这个任务。

1

你可以尝试在 ruby-forum.com 上建议的这段代码,它使用了 WIN32OLE 库。虽然这仅适用于 Windows。

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}"

1

我建议直接使用系统命令包装。
在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接