2

Is there a method to access a function result, which I have applied another function onto it. For example:

win32gui.EnumWindows(a_function, extra)

The EnumWindows will iterate all top-level window and passing hwnd into the a_function.

If I set some condition to grep the hwnd I want, we need to yield the hwnd id

Is there a method to access some return/yield from a_function. Instead of the function EnumWindows will grep the return.

胡亦朗
  • 397
  • 1
  • 3
  • 9

1 Answers1

1

EnumWindows doesn't return anything. The way results are usually retrieved from it is often to make the callback function store data in a global. There's an example of doing that in this question.

Another way is to pass a mutable container object (such as a list) as the extra argument, which will then be passed to the callback as its second argument each time it's called (the first argument is a window handle).

Here's an example using the second technique which passes a local list object to EnumWindows() which the callback function modifies, but only if the window is visible.

import win32gui

def my_callback(hwnd, list_object):
    if win32gui.IsWindowVisible(hwnd):
        title = win32gui.GetWindowText(hwnd)
        if title:
            list_object.append(title)

def print_windows_titles():
    my_list = []  # local variable

    win32gui.EnumWindows(my_callback, my_list)  # populates my_list

    # print result of calling EnumWindows
    print('Titles of Visible Windows:')
    for window_title in my_list:
        print('  {!r}'.format(window_title))

print_windows_titles()
Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Thank you for you answer, It is what I am thinking about. global variable do solve the problem well. As avoiding global variable is a rule of thumb for a beginner, I am thinking about this to figure out whether there is a method to access. manipulation inside the callback and global hwnd is the solution to this questions indeed. – 胡亦朗 Feb 11 '17 at 23:59
  • Do you mean that I can pass an list_object into extra and get the list_object from the function what_i_need_return=win32gui.EnumWindows(a_function, list_object).list_object? – 胡亦朗 Feb 12 '17 at 00:06
  • No. I mean that you can pass a list object to `EnumWindows` and it will be passed to your callback function each time ***it*** is called. But you're right about that being a way of avoiding using a global variable. – martineau Feb 12 '17 at 03:19
  • This is very helpful example. Thanks a lot~ – 胡亦朗 Feb 13 '17 at 12:14