2

如何在 ruby​​ 中获取鼠标指针的位置?

这应该是绝对(屏幕)位置。

如果这需要系统特定的答案,我在 Ubuntu 上。

谢谢

4

1 回答 1

8

我组装了以下功能。它在操作系统上进行调度,并为每个操作系统遵循不同的策略:

require 'rbconfig'

##
# Returns an array [x,y] containing the mouse coordinates
# Be aware that the coordinate system is OS dependent.
def getMouseLocation
  def windows
    require "Win32API"
    getCursorPos = Win32API.new("user32", "GetCursorPos", 'P', 'L')
    # point is a Long,Long-struct
    point = "\0" * 8
    if getCursorPos.Call(point)
      point.unpack('LL')
    else
      [nil,nil]
    end
  end

  def linux
    loc_string = `xdotool getmouselocation --shell`[/X=(\d+)\nY=(\d+)/]
    loc_string.lines.map {|s| s[/.=(\d+)/, 1].to_i}
  end

  def osx
    # if we are running in RubyCocoa, we can access objective-c libraries
    require "osx/cocoa"
    OSX::NSEvent.mouseLocation.to_a
  rescue LoadError
    # we are not running in ruby cocoa, but it should be preinstalled on every system
    coords = `/usr/bin/ruby -e 'require "osx/cocoa"; puts OSX::NSEvent.mouseLocation.to_a'`
    coords.lines.map {|s| s.to_f }
  end

  case RbConfig::CONFIG['host_os']
  when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
    windows
  when /darwin|mac os/
    osx
  when /linux|solaris|bsd/
    linux
  else
    raise Error, "unknown os: #{host_os.inspect}"
  end
rescue Exception => e
  [nil,nil]
end

在 Ubuntu 13.04 (gnome-shell)、Windows 7 64bit、OS x 10.8.4 上测试。如果有人可以确认这适用于其他系统,我会很高兴。也缺少一个 jruby 解决方案。

于 2013-06-30T11:19:41.857 回答