1

I want to be able to do a combination of keypresses and mouseclicks simultaneously, as in for example Control+LeftClick

At the moment I am able to do Control and then a left click with the following code:

import win32com, win32api, win32con
def CopyBox( x, y):
    time.sleep(.2)
    wsh = win32com.client.Dispatch("WScript.Shell")
    wsh.SendKeys("^")
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

What this does is press control on the keyboard, then it clicks. I need it to keep the controll pressed longer and return while it's still pressed to continue running the code. Is there a maybe lower level way of saying press the key and then later in the code tell it to lift up the key such as like what the mouse is doing?

1 Answer 1

3

to press control:

win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)

to release it:

win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0)

so your code will look like this:

import win32api, win32con
def CopyBox(x, y):
    time.sleep(.2)
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)
Sign up to request clarification or add additional context in comments.

4 Comments

The pressing of the control works perfectly, the releasing of it not so much. After the code is run the ctrl key is kept pressed until log-off or restart
Can you verify that it works for you and is not just a problem on my machine?
Seems like the extendedkey thing (Whatever that is) is what caused the problem, it's working perfectly now. Thanks for you answer!
When using the EXTENDEDKEY, you need to provide that as a flag when you want to release the press like: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0), I have suggested an edit of the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.