I found those three ways to get the Mouse Coordinates in Windows:
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def MousePosition_ctypes():
pos = POINT()
windll.user32.GetCursorPos(byref(pos))
return {"x":pos.x,"y":pos.y}
import win32api
def MousePosition_win32api():
pos = win32api.GetCursorPos()
return {"x":pos[0],"y":pos[1]}
import win32gui
def MousePosition_win32gui():
flags, hcursor, (x,y) = win32gui.GetCursorInfo()
return {"x":x,"y":y}
What is the difference between them? Is there an advantage in using ctypes? Is pywin32 doing the same as ctypes here?
I made a timing test with 10^6 runs.
import timeit
print("MousePosition_ctypes ",timeit.repeat("MousePosition_ctypes()", "from __main__ import MousePosition_windll",number=10**6))
print("MousePosition_win32api",timeit.repeat("MousePosition_win32api()", "from __main__ import MousePosition_win32api",number=10**6))
print("MousePosition_win32gui",timeit.repeat("MousePosition_win32gui()", "from __main__ import MousePosition_win32gui",number=10**6))
Results:
MousePosition_ctypes [3.171214059203684, 3.0459668639906723, 3.0454502913267243]
MousePosition_win32api [1.9730332863218454, 1.9517156492346004, 2.072004962338813]
MousePosition_win32gui [1.787176519159173, 1.8011713842243182, 1.8127041221688245]
So the win32gui Version would be the fastest..
I also tested the usecase where it is good to get many cursor coordinates per second. So I measured the mean points per seconds over a minute for each method:
def store_mouse_track_ctypes(t):
t0 = time.time()
list = []
dt = 0
while dt < t:
t1 = time.time()
position = MousePosition_ctypes()
t2 = time.time()
dt = t2 - t0
list.append([t1,t2,position["x"],position["y"]])
return list
a = 60
l = store_mouse_track_ctypes(a)
print("store_mouse_track_ctypes",len(l)/a,"points per second.")
Results:
store_mouse_track_ctypes 169850.01666666666 points per second.
store_mouse_track_win32api 225232.46666666667 points per second.
store_mouse_track_win32gui 231186.85 points per second.
Again win32gui Version is a bit ahead.
Why is the win32gui version the "best"?