I wrote a simple program to get the mouse position using win32api. But I found that sometimes negative values appear. Why is that?
import ctypes
import ctypes.wintypes
import sys
user32 = ctypes.windll.user32
WM_MOUSEMOVE = 0x0200
class POINT(ctypes.Structure):
_fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
class MSLLHOOKSTRUCT(ctypes.Structure):
_fields_ = [("pt", POINT), ("mouseData", ctypes.wintypes.DWORD), ("flags", ctypes.wintypes.DWORD), ("time", ctypes.wintypes.DWORD), ("dwExtraInfo", ctypes.c_ulong)]
def showxy(x, y):
print("x=%d y=%d" % (x, y), end=" r")
def LowLevelMouseProc(nCode, wParam, lParam):
if nCode == 0:
if wParam == WM_MOUSEMOVE:
msl = ctypes.cast(lParam, ctypes.POINTER(MSLLHOOKSTRUCT)).contents
x = msl.pt.x
y = msl.pt.y
showxy(x, y)
elif wParam == 513:
print("Left button pressed")
elif wParam == 0x0204:
print("Right button pressed")
return user32.CallNextHookEx(0, nCode, ctypes.wintypes.WPARAM(wParam), ctypes.wintypes.LPARAM(lParam))
def main():
LRESULT = ctypes.c_long
MYCFUNC = ctypes.CFUNCTYPE(LRESULT, ctypes.wintypes.INT, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)
CFIMCP = MYCFUNC(LowLevelMouseProc)
hook_id = user32.SetWindowsHookExW(14, CFIMCP, None, 0)
msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), None, 0, 0) != 0:
user32.TranslateMessage(msg)
user32.DispatchMessageW(msg)
if __name__ == '__main__':
main()
I only use one monitor. Move the cursor to the screen coordinates and then quickly move it up and down to see negative values.
7