-1

I'm trying to achieve something very simple - with a script I would like to:

  1. Launch a software
  2. Fill out username
  3. Press tab
  4. Fill out password
  5. Press enter

I cannot get steps 3 and 5 to work. Here is my code:

import win32api
import win32gui
import win32con

def send_keys(hwnd, username, password):
    for c in username:
        win32api.PostMessage(hwnd, win32con.WM_CHAR, ord(c), 0)

    win32api.keybd_event(win32con.VK_TAB, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) # DOES NOT WORK
    for c in password:
        win32api.PostMessage(hwnd, win32con.WM_CHAR, ord(c), 0)

    win32api.keybd_event(win32con.VK_RETURN, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) # DOES NOT WORK


def main():
    [...] # Run software, it pops as foreground window
    hwnd = win32gui.GetForegroundWindow()
    send_keys(hwnd, 'some_username', 'some_password')


if __name__ == '__main__':
    main()

When I run the key presses part of script (send_keys) in notepad, it sends tab and return/enter keys properly, however, it does not work for the intended software. Any suggestions?

emihir0
  • 1,200
  • 3
  • 16
  • 39
  • Is one `tab` key press sufficient to get the key focus to your password entry? – import random Nov 19 '17 at 22:11
  • 1
    Why is everyone and their dog obsessed with the idea, that UI Automation should be done by faking input? Why not use UI Automation when you need to automate a UI? – IInspectable Nov 19 '17 at 23:23

1 Answers1

0

PostMessage may return a nonzero value.

The chances are that if you call GetLastError after PostMessage you will get 5=access denied.

In the old days everyone could send message from any app to any windows, but with today security it's most of the time forbidden.

What you want to achieve may be done with the SendInput method.

ColdCat
  • 1,192
  • 17
  • 29