Skip to main content
 首页 » 编程设计

Python win32gui.PostMessage 无法工作

2025年02月15日37sharpest

我想关闭我找到的窗口,这是代码..

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) 

但是错误发生了,

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

我该如何解决? 谢谢

请您参考如下方法:

ctypes 和 win32 hwnds 是不一样的。尝试使用 ctypes.PostMessage 关闭应用程序:

PostMessage = ctypes.windll.user32.PostMessageA 

和

win32gui.PostMessage(hwnd,  win32con.WM_CLOSE,  0,  0)