5

I want to read text labels from another program, with Python. I think I have to use WM_GETTEXT, but I don't know how and I couldn't find anything on the internet. My program gets the active window, but doesn't read the text labels. So I hope that somebody can help me.

EDIT: I have added the buffer and SendMessage Part. I can get the text from Editor for example, but not from the program I am trying to get the text labels from.

I have the following code, which I found here on stackoverflow(Get text from popup window):

import win32gui
import time

while True:
    window = win32gui.GetForegroundWindow()
    title = win32gui.GetWindowText(window)
    if 'GLS Exportdatei' in title:
        control = win32gui.FindWindowEx(window, 0, 'static', None)
        buffer = win32gui.PyMakeBuffer(20)
        length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 20, buffer)

        result = buffer[:length]
        print result
        time.sleep(1)
Community
  • 1
  • 1
Xirama
  • 51
  • 1
  • 7

2 Answers2

5

If the text of your window has more than 20 characters, then the buffer you have created is too small. Try expanding it to more than you're likely to need:

buffer = win32gui.PyMakeBuffer(255)
length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buffer)

If you want to get to the controls within the main window, then use EnumChildWindows, passing the handle of the parent window. You may need to do this recursively.

Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
  • The title is not the problem. It is the textfields I want to get. Here is an example of what the window looks like: [http://imageshack.us/photo/my-images/689/exampleot.png/](http://imageshack.us/photo/my-images/689/exampleot.png/) I try to store these textfields in the result variable. – Xirama Jan 24 '13 at 14:54
  • @Xirama, whether the text is a title or the contents of the window depends on the window type. It's the same call either way. – Mark Ransom Jan 24 '13 at 16:45
  • Many thanks for all your help. I now use EnumChildWindows to get the controls. – Xirama Feb 06 '13 at 14:30
2

win32gui.PyMakeBuffer has been deprecated. Also, buffer is a builtin function, so don't use it as a variable name.

Instead, just do this:

buf = " " * 255
length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buf)
result = buf[:length]
twasbrillig
  • 17,084
  • 9
  • 43
  • 67