You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用字符串变量调用win32gui调整窗口大小失败,报错无效窗口句柄

问题

希望通过字符串变量调整任意窗口大小,但win32gui无法正确识别字符串。

代码实现
import linecache
import os
import win32gui

desktop = os.path.expanduser("~\Desktop")

def resize_pg(N4, x, y, w, h):
    hwnd = win32gui.FindWindow(None, N4)
    win32gui.MoveWindow(hwnd, x, y, w, h, True)
    print(N4)
    
file_path = desktop+('\Re.txt')
ref_1 = linecache.getline(file_path,1)
ref_2 = linecache.getline(file_path,2)
resize_pg(ref_1 , 0, 0, 420, 336)
Re.txt内容
A.txt - Notepad
B.txt - Notepad
报错信息
Traceback (most recent call last):
  File "c:\Users\Desktop\UUU.py", line 16, in <module>
    resize_pg(ref_1, 0, 0, 420, 336)
  File "c:\Users\Desktop\UUU.py", line 9, in resize_pg
    win32gui.MoveWindow(hwnd, x, y, w, h, True)
pywintypes.error: (1400, 'MoveWindow', 'Invalid window handle.')
解决方法

核心问题是linecache.getline读取每行时会保留末尾的换行符\n,导致窗口标题不匹配,FindWindow返回无效句柄。

修改后的代码:

import linecache
import os
import win32gui

desktop = os.path.expanduser("~\Desktop")

def resize_pg(N4, x, y, w, h):
    # 去除标题首尾的空白字符(包括换行符)
    clean_title = N4.strip()
    hwnd = win32gui.FindWindow(None, clean_title)
    # 先检查窗口句柄是否有效
    if hwnd:
        win32gui.MoveWindow(hwnd, x, y, w, h, True)
        print(f"已调整窗口:{clean_title}")
    else:
        print(f"未找到对应窗口:{clean_title}")
    
# 用os.path.join拼接路径更稳妥,兼容不同系统
file_path = os.path.join(desktop, 'Re.txt')
ref_1 = linecache.getline(file_path,1)
ref_2 = linecache.getline(file_path,2)
resize_pg(ref_1 , 0, 0, 420, 336)

关键改动:

  1. 对读取到的标题字符串调用strip(),移除换行符和首尾空格
  2. 增加窗口句柄有效性判断,避免无效句柄触发报错
  3. 改用os.path.join拼接文件路径,避免路径分隔符问题

内容的提问来源于stack exchange,提问作者Komsan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:36:29