7
12

More than 1 year has passed since last update.

Pythonで特定のソフトをアクティブにする方法

Posted at

Pythonで自動入力等をしたいときに、目的のソフトをアクティブにする方法の覚書き

その1 自動クリックでアクティブにする

【Python】Windows10:アプリケーションを最前面に表示・アクティブ化させる方法が分かりやすい。

active.py
import win32gui
import win32con
import pyautogui
import ctypes

def foreground():
    hwnd = ctypes.windll.user32.FindWindowW("目的のWindowタイトル", 0)
    win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,0,0,win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
    #2つ目の要素の内容
    #HWND_TOPMOST:ウィンドウを常に最前面にする。
    #HWND_BOTTOM:ウィンドウを最後に置く。
    #HWND_NOTOPMOST:ウィンドウの最前面解除。
    #HWND_TOP:ウィンドウを先頭に置く。

    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    win32gui.SetForegroundWindow(hwnd)
    pyautogui.moveTo(left+60, top + 10)
    pyautogui.click()

PyAutoGUIについては、Pythonでマウスやキーボードを操作できるPyAutoGUIによる自動操作マニュアルがとても参考になった。

その2 特定のタイトルを持つウィンドウを最前面にする(常にではない)

任意の文字の含まれたウインドウを最前列に持って行く関数を作りたい。その文字列を引数として渡す場合は?を参照。

Active2.py
import win32gui
import ctypes
def forground( hwnd, title):
    name = win32gui.GetWindowText(hwnd)
    if name.find(title) >= 0:
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd,1) # SW_SHOWNORMAL
        ctypes.windll.user32.SetForegroundWindow(hwnd)
        return False

win32gui.EnumWindows( forground, 'タイトルの一部')

最後に、ウィンドウクラスやタイトルをすべて取得するコード
調べてくれた先人に感謝です。

titleGet.py
import win32gui

win32gui.EnumWindows(lambda x, _: print(str(x)+' : '+win32gui.GetClassName(x)+' : '+win32gui.GetWindowText(x)), None)

ウィンドウタイトルだけならこっちもあり

get_window_title.py
import ctypes
def get_window_title():

    EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))

    EnumWindows = ctypes.windll.user32.EnumWindows
    # タイトル格納用変数
    title = []
    def foreach_window(hwnd, lparam):
        if ctypes.windll.user32.IsWindowVisible(hwnd):
            length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
            buff = ctypes.create_unicode_buffer(length +1)
            ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
            title.append(buff.value)
            return True
    EnumWindows(EnumWindowsProc(foreach_window), 0)
    print(title)

if __name__ == '__main__':
    get_window_title()
7
12
1

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
7
12