LoginSignup
1
0

More than 1 year has passed since last update.

Python でウィンドウの閉じるボタンを無効化する

Last updated at Posted at 2022-01-27

概要

Minecraftで遊んでいるとき、間違えてウィンドウの閉じるボタンを押してしまうと何の確認もなくゲームが終了してしまいます。これを防止するために閉じるボタンを無効化します。

前提

Microsoft Windows 10 Home
Python 3.7.7
pip 21.3.1

pywin32 のインストール

pip install pywin32

プログラム

disableXbutton.py
import win32con
import win32gui

from typing import Union


def getHwnd(title: str) -> Union[int, None]:
    hwnd = win32gui.FindWindow(None, title)
    if not hwnd:
        return None
    return hwnd


def showXbutton(hwnd: int) -> None:
    win32gui.GetSystemMenu(hwnd, True)


def disableXbutton(hwnd: int) -> None:
    win32gui.GetSystemMenu(hwnd, True)
    hMenu = win32gui.GetSystemMenu(hwnd, 0)
    if not hMenu:
        print("couldn't find menu.")
        return

    win32gui.DeleteMenu(hMenu, win32con.SC_CLOSE, win32con.MF_BYCOMMAND)


def main():
    titles = []
    with open("titles.txt", mode="r") as f:
        titles = f.readlines()
        titles = list(map(lambda x: x.replace("\n", ""), titles))

    for title in titles:

        hwnd = getHwnd(title)
        if not hwnd:
            print("couldn't find window:", title)
            continue

        disableXbutton(hwnd)
        print("Disabled Xbutton: " + win32gui.GetWindowText(hwnd))

        # 無効化した閉じるボタンを有効化する関数
        # showXbutton(title)


if __name__ == '__main__':
    main()

titles.txt
Minecraft* 1.17.1 - Multiplayer (3rd-party Server)

ウィンドウ名の調べ方

titles.txt に入力するウィンドウ名は、おそらく完全なものである必要があります。そのために、Visual Studio に同梱されている Microsoft Spy++(公式ドキュメント)を使用します。

image.png

1.

image.png
image.png

ウィンドウ検索 を開き ファインダー ツール を調べたいウィンドウの上にドラッグし、OK を押します。

2.

image.png

OK を押すと プロパティインスペクター が表示され、ウィンドウキャプション が調べたかったウィンドウ名となります。

実行

image.png

実行すると、閉じるボタンが灰色になり無効化されます。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0