Ruby - 获取鼠标坐标

时间:2013-06-30 08:17:04

标签: ruby

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

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

如果这需要特定于系统的答案,我会使用Ubuntu。

由于

1 个答案:

答案 0 :(得分: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(point)
      a.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 64位,OS x 10.8.4。我很高兴,如果有人能确认这适用于其他系统。缺少一个犹豫不决的解决方案。