Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

win32gui.FindWindow Not finding window

I'm trying to send a keystroke to an inactive TeraTerm Window using Pywin32.

This answer led me to write this code:

import win32gui
import win32con
import win32api

hwndMain = win32gui.FindWindow("Tera Term VT", None)
print hwndMain
hwndChild = win32gui.GetWindow(hwndMain, win32con.GW_CHILD)
win32api.PostMessage(hwndChild, win32con.WM_CHAR, 0x5b, 0)

but:
hwndMain = win32gui.FindWindow("Tera Term VT", None) returns 0, it can't find the window.

If I change "Tera Term VT" to "Notepad", I can happily send keystrokes to an active Notepad window all day long. So, why can't I get the TeraTerm window?

According to the ActiveState documentation:

PyHANDLE = FindWindow(ClassName, WindowName)

ClassName : PyResourceId Name or atom of window class to find, can be None
WindowName : string Title of window to find, can be None

So how can I get the correct ClassName to use?

I've tried just about every variation of Tera Term VT, escaping the spaces: "Tera\ Term\ VT", enclosing the whole in single quotes: "'Tera Term VT'", but nothing works. I've even tried using the name of the process:"ttermpro.exe", and included the child name in the string "COM11:115200baud - Tera Term VT" in my desperation, but nothing works.

Interestingly, this:

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("Tera Term VT")
shell.SendKeys("\%i", 0)

works just fine, but brings the window to the foreground, which I don't wan't. The Tera Term VT string works fine in this instance though.

like image 890
SiHa Avatar asked Aug 16 '16 08:08

SiHa


1 Answers

The line

shell.AppActivate("Tera Term VT")

works on the window title and therefore it works.
You should be able to to the same with

hwndMain = win32gui.FindWindow(None, "Tera Term VT")  

that is, swapping the arguments so that it also works based on the window title

If you want to work based on the window class name you could use a tool like Spy++ with its Finder Tool to target the Tera Term window and get its window class name from the properties

like image 183
DAXaholic Avatar answered Oct 12 '22 12:10

DAXaholic