Python Win32 send keystrokes to Chrome

4.6k Views Asked by At

I am trying to run a python script in Windows to send an F5 command to a Google Chrome v53 window. But unfortunately nothing happens. But it works like a charm with Internet Explorer v11 (after changing the Class Name).

Python code

import win32gui, win32api, win32con
hwnd = win32gui.FindWindow("Chrome_WidgetWin_1", None)
print hwnd
# Sending command to the main windows also does not work
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F5, 0)
hwnd = win32gui.FindWindowEx(hwnd, None, "Chrome_RenderWidgetHostHWND", None)
print hwnd
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F5, 0)

Python output

1181972
0

EDIT: Included hidden windows

There seems to be more windows, that have the same Class Name. Therefore, I am now searching not only by the Class Name, but also by the Text. The first attempt did only find a window, which did not have any children. Therefore the second line of the output had a 0.

Altered Python code

import win32gui, win32api, win32con
hwnd = win32gui.FindWindow("Chrome_WidgetWin_1", "Stack Overflow - Google Chrome")
print hwnd
# Sending command to the main windows also does not work
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F5, 0)
hwnd = win32gui.FindWindowEx(hwnd, None, "Chrome_RenderWidgetHostHWND", None)
print hwnd
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F5, 0)

Python output

1247302
1509536

EDIT: SetForegroundWindow solution

The solution for the problem was first to set the window to foreground by win32gui.SetForegroundWindow(Handle) method and then to send the key commands.

But still, no commands are passed to the window and the website is not refreshed.

1

There are 1 best solutions below

1
Zelix75 On

You can use this

import pyautogui
pyautogui.hotkey('f5')

This will simulate your refresh key, sending the signal to chrome.
In case you don't want the chrome window to be made active, then when you START chrome, start it by typing this in the command prompt:

start /B chrome.exe

Then close chrome. It will run in the background. When the work is done, go Task Manager and close chrome.
OR you could go to Chrome>Advanced>System and see the first option.