Method of closing third party window by python

  • 2021-07-03 00:40:08
  • OfStack

Background

Recently, I tested the function of closing the third window of 1 software, and I feel that it should be quite simple to realize it. So I tried. Because it is achieved by c + +, I am really not good at c + +, but the third party library of python actually encapsulates a set of win32 api, so we can still rely on python to achieve this.

Realization

It's very simple to post the code directly


# -*- coding: utf-8 -*-
from win32gui import *
import win32gui
import win32con
from time import sleep

def foo(hwnd,mouse):
  global config_contents
  if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
    for content in config_contents:
      ads_info = []
      if not '|' in content :
        continue
      else:
        ads_info = content.split('|')
      if GetClassName(hwnd)==ads_info[1] and GetWindowText(hwnd)==ads_info[0]:
        win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)


config_file = open("C:\\1.txt","r")
config_contents = config_file.readlines()
while 1:
  EnumWindows(foo, 0)
  sleep(0.5)

Here we read the configuration file of the third party directly, and the content of the configuration file is written in the form of window title window class name. Therefore, we directly judge whether the window class name is related to the configuration file 1, and if 1 is related, we will send the command to close the window.


Related articles: