Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python win32gui.PostMessage can't work

I want to close the window which I found , here is the code ..

import ctypes
import win32gui, win32con, win32api

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible

titles = []
user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32

def foreach_window(hwnd, lParam):
    if IsWindowVisible(hwnd):
        length = GetWindowTextLength(hwnd)
        buff = ctypes.create_unicode_buffer(length + 1)
        GetWindowText(hwnd, buff, length + 1)
        titles.append(buff.value)
        if (buff.value == '123.txt'):
            print('I got u...')
            win32gui.PostMessage(hwnd,  win32con.WM_CLOSE,  0,  0)
    return True

EnumWindows(EnumWindowsProc(foreach_window), 0)

but the error occur ,

win32gui.PostMessage(hwnd,  win32con.WM_CLOSE,  0,  0)
TypeError: The object is not a PyHANDLE object

how can I solve it ? thanks

like image 876
Relax ZeroC Avatar asked Jun 28 '26 22:06

Relax ZeroC


1 Answers

ctypes and win32 hwnds are not the same. Try to close the application using ctypes.PostMessage:

PostMessage = ctypes.windll.user32.PostMessageA

and

win32gui.PostMessage(hwnd,  win32con.WM_CLOSE,  0,  0)
like image 129
Maurice Meyer Avatar answered Jul 01 '26 12:07

Maurice Meyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!