Detecting Mouse clicks in windows using python

How can I detect mouse clicks regardless of the window the mouse is in?

Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.

I found this on microsoft's site:

But I don't see how I can detect or pick up the notifications listed.

Tried using pygame's pygame.mouse.get_pos() function as follows:

import pygame
while True:
    print pygame.mouse.get_pos()

This just returns 0,0. I'm not familiar with pygame, is something missing?

In anycase I'd prefer a method without the need to install a 3rd party module. (other than pywin32 )

Asked by: Marcus251 | Posted: 28-01-2022

Answer 1

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx. The pyHook module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click:

import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()

You can check the script that is installed with the module for more info about the event parameter.

pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the tutorial:

Any application that wishes to receive notifications of global input events must have a Windows message pump. The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python. [...] When run, this program just sits idle and waits for Windows events. If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own.

Answered by: Tara716 | Posted: 01-03-2022

Answer 2

I use win32api. It works when clicking on any windows.

# Code to check if left or right mouse buttons were pressed
import win32api
import time

state_left = win32api.GetKeyState(0x01)  # Left button down = 0 or 1. Button up = -127 or -128
state_right = win32api.GetKeyState(0x02)  # Right button down = 0 or 1. Button up = -127 or -128

while True:
    a = win32api.GetKeyState(0x01)
    b = win32api.GetKeyState(0x02)

    if a != state_left:  # Button state changed
        state_left = a
        if a < 0:
            print('Left Button Pressed')
            print('Left Button Released')

    if b != state_right:  # Button state changed
        state_right = b
        if b < 0:
            print('Right Button Pressed')
            print('Right Button Released')

Answered by: Hailey913 | Posted: 01-03-2022

Answer 3

It's been a hot minute since this question was asked, but I thought I'd share my solution: I just used the built-in module ctypes. (I'm using Python 3.3 btw)

import ctypes
import time

def DetectClick(button, watchtime = 5):
    '''Waits watchtime seconds. Returns True on click, False otherwise'''
    if button in (1, '1', 'l', 'L', 'left', 'Left', 'LEFT'):
        bnum = 0x01
    elif button in (2, '2', 'r', 'R', 'right', 'Right', 'RIGHT'):
        bnum = 0x02

    start = time.time()
    while 1:
        if ctypes.windll.user32.GetKeyState(bnum) not in [0, 1]:
            # ^ this returns either 0 or 1 when button is not being held down
            return True
        elif time.time() - start >= watchtime:
    return False

Answered by: Lucas515 | Posted: 01-03-2022

Answer 4

Windows MFC, including GUI programming, is accessible with python using the Python for Windows extensions by Mark Hammond. An O'Reilly Book Excerpt from Hammond's and Robinson's book shows how to hook mouse messages, .e.g:


Raw MFC is not easy or obvious, but searching the web for python examples may yield some usable examples.

Answered by: Alford186 | Posted: 01-03-2022

Answer 5

The windows way of doing it is to handle the WM_LBUTTONDBLCLK message.

For this to be sent, your window class needs to be created with the CS_DBLCLKS class style.

I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.

Answered by: Brad514 | Posted: 01-03-2022

Similar questions

windows - Detecting if the win7 desktop is shown with python and Qt

I want to check if the desktop of Windows 7 is shown (e.g. after clicking control+D or the showDesktop-Button). It is meant for an application where I've set the QtCore.Qt.FramelessWindowHint to make the decorations disappear. After the desktop is shown and everything is minimized, I want to reshow the app (This should be optional and the user can set or unset this behaviour). I tested this in IDLE. I want ...

java - Detecting system sound on Windows using Python

Is there any way to detect system sound instead of microphone sound? I want to be able to detect whenever my system makes a sound instead of when the microphone picks up the actual sound. One way I found to do this use an "audio loop-back in either software or hardware (e.g. connect a lead from the speaker 'out' jack to the microphone 'in' jack)."

windows - Detecting User Idle Time in Python

The following Python code is supposed to print out how much time has passed since the last user activity (mouse movement, keyboard keys pressed) from ctypes import Structure, windll, c_uint, sizeof, byref import time class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_uint), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.c...

audio - Detecting Windows System sounds with Python

I have a python script that pulls the cell values from a spreadsheet and inputs it into a program. Problem is that if there is an error that occurs when the information is being input (duplicate value, navigational error, sql error, etc) the script will not recognize that there is an error and just keep running. I'd like to find a way to have the script recognize when these errors occur and hold the script or take another ...

windows - detecting a message box or ok button using python

I am an avid python programmer and have been delving into the Windows Api for Python and have been stuck on detecting if an "OK" button or message box has appeared within my computer (whether that be from a third party application or windows). I know that you can use any of these below to control parts of your computer via mouse clicks and such. import win32api, win32com, win32con, ctypes

Python windows path not detecting

I am using wathdog to detect new files, modified files using watchdog python module in windows operating system. But it is unable to detect file path my code and located at something like L:\my_code\ (in L drive ) import time from watchdog.observers import Observer from import PatternMatchingEventHandler def on_created(event): print(f&quot;hey, {event.src_pat...

windows - Detecting symlinks (mklink) on Vista/7 in Python without Pywin32

Currently the buildout recipe collective.recipe.omelette uses junction.exe on all versions of Windows to create symlinks. However junction.exe does not come with Windows by default and most importantly does not support creating symlinks to files (only directories) which causes a problem with quite a few Python packages. On NT6+ (Vista and 7) there is now the mklink utility that not only comes by default but is also...

Detecting the http request type (GET, HEAD, etc) from a python cgi

How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET. Thanks!

python - detecting end of tty output

Hi I'm writing a psudo-terminal that can live in a tty and spawn a second tty which is filters input and output from I'm writing it in python for now, spawning the second tty and reading and writing is easy but when I read, the read does not end, it waits for more input. import subprocess pfd = subprocess.Popen(['/bin/sh'], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) cm...

gcc - Detecting Infinite recursion in Python or dynamic languages

Recently I tried compiling program something like this with GCC: int f(int i){ if(i&lt;0){ return 0;} return f(i-1); f(100000); and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f. And - the compiler wasn't even running in optimiz...

python - Detecting mulitple cycles in a cyclic directed graph

I have a directed cyclic graph with more than one cycle in it and I need a way to detect (and list) each cycle present in the digraph. The graph can be seen here: This is a dummy graph put together for the sake of debugging my python script. It contains the cycl...

Detecting timeout erros in Python's urllib2 urlopen

I'm still relatively new to Python, so if this is an obvious question, I apologize. My question is in regard to the urllib2 library, and it's urlopen function. Currently I'm using this to load a large amount of pages from another server (they are all on the same remote host) but the script is killed every now and then by a timeout error (I assume this is from the large requests). Is there a way to keep the ...

python - Detecting Similar images

This question already has answers here:

python - better for-loop syntax for detecting empty sequences?

Is there a better way to write the following: row_counter = 0 for item in iterable_sequence: # do stuff with the item counter += 1 if not row_counter: # handle the empty-sequence-case Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known lengths; 2) in some cases calling len() may trigger loading of the sequence's i...

python - Detecting whether or not text is English (in bulk)

I'm looking for a simple way to detect whether a short excerpt of text, a few sentences, is English or not. Seems to me that this problem is much easier than trying to detect an arbitrary language. Is there any software out there that can do this? I'm writing in python, and would prefer a python library, but something else would be fine too. I've tried google, but then realized the TOS didn't allow automated queries.

python - Detecting Type of Video Stream

I have 2 video streams (1) VLC Generated Compressed MP4 UDP stream (2) DV Uncompressed UDP Stream Both are destined to a host. At this Unix receiving host, I would like to detect type of stream coming using Bash or Python Scripting (without tcpdump, I do not have root priv.) ANY idea guys how to implement ? Thank you.

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python