2013-06-30 73 views
2

如何獲得鼠標指針在紅寶石中的位置?紅寶石 - 獲取鼠標座標

這應該是絕對的(屏幕)位置。

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

謝謝

+0

您可以使用gem * selenium-webdriver *。 –

+4

除非特定的GUI系統被指定,否則這個問題沒有意義。 – sawa

+1

http://stackoverflow.com/questions/8480073/how-would-i-get-the-current-mouse-coordinates-in-bash – Casper

回答

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),道64位Windows 7,Mac OS X 10.8.4。如果有人能證實這在其他系統上有效,我會很高興。 jruby解決方案也丟失了。

+0

我很確定這不會在Windows上工作。 'xdotool'聽起來不像Windows那樣。 –

+0

對,我應該提到Windows不支持。你知道如何在Windows上做到這一點?那麼我們可以在OS上做一些調度。 – tessi

+0

'GetCursorPos'是Windows的等價物:http://msdn.microsoft.com/en-us/library/ms648390%28VS.85%29.aspx –