Simulate Mouse Clicks on Python

Controlling mouse with Python

Tested on WinXP, Python 2.6 (3.x also tested) after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):

import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)

Simulating mouse click using python and win32api

Well, I found the problem.

With the example trying to send the letter C to notepad and the chrome browser I assumed that the first hwnd is the right one BUT in some cases, you have to interact with a child window. A window may have more than one child window, so, I will post a code here where you can find the window to interact with.

import win32gui
import win32con
import win32api
import time

def send_char(hwnd, lparam):
s = win32gui.GetWindowText(hwnd)
print("child_hwnd: %d txt: %s" % (hwnd, s))
win32api.PostMessage(hwnd, win32con.WM_CHAR, ord('c'), 0)
time.sleep(5)
return 1

def main():
main_app = 'Untitled - Notepad'
hwnd = win32gui.FindWindow(None, main_app)
if hwnd:
win32gui.EnumChildWindows(hwnd, send_char, None)

main()

With that you can find the child window that you should send the messages to (the code print the window id and name, send the character and wait 5 seconds, so when you notice the character on your window just get the last printed window id and use it instead of the parent window).

I hope it help someone facing the same problem.

How to make python script that performs a Mouse Click in Windows 10?

Try this way:

import pywinauto
app = pywinauto.Application().connect(path='your_process_name.exe')
app.MainDialog.click_input(coords=(x, y))

For click method to work you need to specify the process/dialog on which the coordinate is present.
Use connect() method to connect to a existing method else use start() to open new instance.



Related Topics



Leave a reply



Submit