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

如何在OpenCV-Python中禁用Windows窗口的最大化按钮

解决Windows下OpenCV窗口禁用最大化按钮的问题

OpenCV的cv2.imshow默认创建的窗口带有最大化按钮,要在Windows系统下禁用这个按钮,需要通过调用Windows系统API修改窗口样式。以下是修改后的完整代码:

import requests
import cv2
import numpy as np
import imutils
import ctypes
import time

def disable_maximize_button(window_title):
    # 根据窗口标题获取句柄
    hwnd = ctypes.windll.user32.FindWindowW(None, window_title)
    if hwnd == 0:
        return False
    
    # 定义窗口样式常量
    GWL_STYLE = -16
    WS_MAXIMIZEBOX = 0x00010000
    
    # 获取当前窗口样式并移除最大化按钮标志
    current_style = ctypes.windll.user32.GetWindowLongPtrW(hwnd, GWL_STYLE)
    new_style = current_style & ~WS_MAXIMIZEBOX
    
    # 应用新样式并刷新窗口
    ctypes.windll.user32.SetWindowLongPtrW(hwnd, GWL_STYLE, new_style)
    ctypes.windll.user32.SetWindowPos(hwnd, 0, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040)
    return True

print('在Play商店安装Ip Webcam并启动服务器。注意:手机和电脑要连接同一WiFi')
# 替换为你的手机摄像头IP地址,例如"http://192.168.1.105:8080"
source = "http://your_mobile_ip:8080"
url = f"{source}/shot.jpg"
window_title = "Mobi-CCTV"
maximize_disabled = False

while True:
    img_resp = requests.get(url)
    img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)
    img = cv2.imdecode(img_arr, -1)
    img = imutils.resize(img, width=1000, height=1800)
    cv2.imshow(window_title, img)
    
    # 仅在首次显示窗口时禁用最大化按钮
    if not maximize_disabled:
        time.sleep(0.1)  # 等待窗口创建完成
        maximize_disabled = disable_maximize_button(window_title)
    
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()

关键说明:

  • 借助ctypes调用Windows的user32.dll库,直接操作窗口样式:
    • FindWindowW通过标题定位窗口句柄
    • GetWindowLongPtrW获取当前窗口样式
    • 移除WS_MAXIMIZEBOX标志位来禁用最大化按钮
    • SetWindowPos刷新窗口以应用样式变更
  • 用maximize_disabled标记确保只执行一次样式修改,避免重复操作
  • time.sleep(0.1)是为了等待窗口完全创建,防止找不到句柄

注意事项:

  1. 务必将source替换为你的手机IP Webcam提供的实际地址
  2. 该方案仅适用于Windows系统,依赖Windows专属API
  3. 窗口标题必须和cv2.imshow的参数完全一致,区分大小写
  4. 如果仍无法生效,可适当延长time.sleep的时长(如0.2秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:06:26