-2

I'm making a code in python to simulate a mouse press to a window. My current code is:

def MousePress_Pos(x, y):
    pos = MAKELONG(x, y)
    SendMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, pos)
    SendMessage(hwnd, WM_LBUTTONUP, MK_LBUTTON, pos)

This code is successfully simulating a mouse press but it doesn't do it on the given X and Y. Instead, it presses on the current X and Y of my mouse!

This is also happening when the window is not focused. It just ignores the given X and Y and presses on the window with the mouse's X and Y.

I have no idea why this happens. Does anybody know what should I do? Thanks.

Flafy
  • 176
  • 1
  • 3
  • 15
  • [You can't simulate keyboard input with PostMessage](https://devblogs.microsoft.com/oldnewthing/20050530-11/?p=35513). With that out of the way, your first order of action should be to determine, whether you can use [UI Automation](https://learn.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32). – IInspectable Jun 30 '20 at 07:47

1 Answers1

0

Use SendInput instead of SendMessage to simulate mouse input.

The following is an example in C++ you can refer to:

int sx = GetSystemMetrics(SM_CXSCREEN);
int sy = GetSystemMetrics(SM_CYSCREEN);

long x_calc = x * 65536 / sx;
long y_calc = y * 65536 / sy;

INPUT mi = { 0 };
mi.type = INPUT_MOUSE;
mi.mi.dx = x_calc;
mi.mi.dy = y_calc;
mi.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN;

SendInput(1, &mi, sizeof(mi));

mi.mi.dwFlags = MOUSEEVENTF_LEFTUP;

SendInput(1, &mi, sizeof(mi));

Refer to the following two threads for how to achieve the same work in Python.

First one:

import math
#...
    x_calc = math.floor(65536 * x_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CXSCREEN) + 1)
    y_calc = math.floor(65536 * y_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CYSCREEN) + 1)

Second one:

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))
Rita Han
  • 9,574
  • 1
  • 11
  • 24