0

I have written a small function that gets the current position of the mouse cursor and prints it to a command line. However I want to also be able to press a key at any point and it will run a function. However if there is no key press I want it to continue running the function and printing the position of the mouse...

Code for the mouse pos:

while True :
    x, y = win32api.GetCursorPos()
    data = (str(x) + " " + str(y))
    print data
    time.sleep(0.1)

The code I added for the key press was this:

while True :
    if msvcrt.getch() == "h" :
        data = "h"
    else :
        x, y = win32api.GetCursorPos()
        data = (str(x) + " " + str(y))
    print data
    time.sleep(0.1)

However the problem with this is that it waits until I press a key to run the get cursor position. It also doesn't register a key press of h when the program is unfocused which is a necessity.

Thanks for any help,

Ryan.

cookies
  • 347
  • 1
  • 6
  • 18
  • possible duplicate of [Applying low-level keyboard hooks with Python and SetWindowsHookExA](http://stackoverflow.com/questions/9817531/applying-low-level-keyboard-hooks-with-python-and-setwindowshookexa) – Peter Wood Aug 06 '15 at 16:05
  • So, you want `h` to do something any time you press it? How would you be able to type? I guess if that's what you want though, you need to [register a hook](https://msdn.microsoft.com/en-us/library/windows/desktop/ms644990(v=vs.85).aspx). – Peter Wood Aug 06 '15 at 16:07
  • @PeterWood Would a hook work if the console was unfocused? And yes when h is pressed I want it to run a function otherwise keep getting the position of the mouse – cookies Aug 06 '15 at 16:13

2 Answers2

0

You should try "PyAutoGUI"

PyAutoGUI can help you control Mouse and Keyboard Hope this can help you

0

In the past, I've used the pynput module for sending and listening for key presses and mouse clicks.

To get the mouse position, you would use:

from pynput import*
mouse_controller=mouse.Controller()
print mouse_controller.position

To send a key press, you would use:

from pynput import*
keyboard_controller=keyboard.Controller()
keyboard_controller.type("Something")

You can see more on the pynput module by clicking the link.

Professor Dragon
  • 217
  • 1
  • 4
  • 14