# Setting the mouse position

**URL:** <https://www.ruby-forum.com/t/setting-the-mouse-position/51167>\
**Category:** Ruby\
**Created:** [December 27, 2005, 2:40pm UTC](https://www.ruby-forum.com/t/setting-the-mouse-position/51167 "2005-12-27T14:40:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gues](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4da419/32.png) [@Gues](https://www.ruby-forum.com/u/Gues)\
**Post date:** [December 27, 2005, 2:40pm UTC](https://www.ruby-forum.com/t/setting-the-mouse-position/51167/1 "2005-12-27T14:40:58Z")

</div>

Hi,

How can I set the mouse position? So change the mouse to a specified  
(x,y) on the screen?

Also,

How can I get the location of a window on the screen of which I know the  
title?

Thanks.

---

<div class="post-metadata">

**Author:** ![Gues](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/4da419/32.png) [@Gues](https://www.ruby-forum.com/u/Gues)\
**Post date:** [December 27, 2005, 6:57pm UTC](https://www.ruby-forum.com/t/setting-the-mouse-position/51167/2 "2005-12-27T18:57:20Z")

</div>

I assume you are asking about Microsoft Windows. This is a very  
specific question which is more related to Windows programming and the  
Windows API than Ruby programming. But nonetheless:

1. To set the mouse position you need the SetCursorPos function, which  
you can access from Ruby like so:

require ‘Win32API’

setCursorPos = Win32API.new(“user32”, “SetCursorPos”, [‘I’,‘I’], ‘V’)  
setCursorPos.Call(100,100)

1. To get the location of a Window whose title you know, do the  
following:

require ‘Win32API’

findWindow = Win32API.new(“user32”, “FindWindow”, [‘P’,‘P’], ‘L’)  
getClientRect = Win32API.new(“user32”, “GetClientRect”, [‘P’,‘P’], ‘V’)  
hwnd = findWindow.Call(nil, ‘name of window here’)  
lpRect = " " \* 16 # Four LONGs  
getClientRect.Call(hwnd, lpRect)  
left, top, right, bottom = lpRect.unpack(‘LLLL’)  
puts “Left: #{left}, Top: #{top}, Right: #{right}, Bottom: #{bottom}”

Ryan
