mouse control with python

K

Ken Favrow

Is there a way I can control the mouse with python? I need to be able to
navigate and click in other applications based on vectors sent from my
program. Basically a mouse macro type thing.

any help?
 
K

Ken Favrow

Very nice. Very helpful! Thank you!!

I ran around looking at ctypes and the User32 dll looking for mouse click
control and couldn't find anything. Is there a way for me to send a mouse
click too?


Richie Hindle said:
[Ken]
Is there a way I can control the mouse with python?

I assume you're on Windows. Here's how to move the mouse:

You can get ctypes from http://starship.python.net/crew/theller/ctypes/

As an added bonus, here's something that moves it relative to the
currently-focussed window, which is probably useful for what you want
(note that this one doesn't work on 95 or NT4 pre SP3, and it could use
some error handling).

from ctypes import *

user32 = windll.user32
kernel32 = windll.kernel32

class RECT(Structure):
_fields_ = [
("left", c_ulong),
("top", c_ulong),
("right", c_ulong),
("bottom", c_ulong)
]

class GUITHREADINFO(Structure):
_fields_ = [
("cbSize", c_ulong),
("flags", c_ulong),
("hwndActive", c_ulong),
("hwndFocus", c_ulong),
("hwndCapture", c_ulong),
("hwndMenuOwner", c_ulong),
("hwndMoveSize", c_ulong),
("hwndCaret", c_ulong),
("rcCaret", RECT)
]

def moveCursorInCurrentWindow(x, y):
# Find the focussed window.
guiThreadInfo = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO))
user32.GetGUIThreadInfo(0, byref(guiThreadInfo))
focussedWindow = guiThreadInfo.hwndFocus

# Find the screen position of the window.
windowRect = RECT()
user32.GetWindowRect(focussedWindow, byref(windowRect))

# Finally, move the cursor relative to the window.
user32.SetCursorPos(windowRect.left + x, windowRect.top + y)

if __name__ == '__main__':
# Quick test.
moveCursorInCurrentWindow(100, 100)


Hope that helps,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top