0
0

More than 1 year has passed since last update.

【Python・Windows】指定ウィンドウを最上部に固定して作業効率を上げるスクリプト

Last updated at Posted at 2021-09-29

はじめに

画像などを参考・参照しながら作業したいことってありますよね。
Windowsでは基本的にフォーカスされているウィンドウが最上部に出てくるため、画面を分割表示するなどしないといけません。捗りません。
その画像などが横長ならまだしも、縦長だと目も当てられません。

そこで、ショートカットキーで最上部ウインドウを設定できる簡単なスクリプトを書きました。

できたもの

import win32gui
import win32con
import win32api
import time


class TopLevelWindows:

    def __init__(self):
        self.top_window = None

    def toggle(self):
        if self.top_window:
            self.__unset_z_pos_0()
        else:
            self.__set_z_pos_0()
        return

    def __set_z_pos_0(self):
        self.top_window = win32gui.GetForegroundWindow()
        win32gui.SetWindowPos(self.top_window, win32con.HWND_TOPMOST, 0,
                              0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
        print(win32gui.GetWindowText(self.top_window), 'is setted to top.')
        return

    def __unset_z_pos_0(self):
        try:
            win32gui.SetWindowPos(self.top_window, win32con.HWND_NOTOPMOST, 0,
                                  0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
            print(win32gui.GetWindowText(self.top_window), 'is unsetted to top.')
            self.top_window = None
        except Exception as e:
            print(e)
        return

    def quit(self):
        if self.top_window:
            self.__unset_z_pos_0()
        return


def get_key_state(keycode):
    return win32api.GetAsyncKeyState(keycode) >> 15 < 0


if __name__ == '__main__':
    w = TopLevelWindows()
    flag = False
    hz = 2000
    hz_high = int(hz*2**(7/12))
    ms = 100

    while True:
        time.sleep(.5)
        if get_key_state(18) and get_key_state(84): # alt+t

            w.toggle()
            if flag:
                win32api.Beep(hz_high, ms)
                win32api.Beep(hz, ms)
                flag = False
            else:
                win32api.Beep(hz, ms)
                win32api.Beep(hz_high, ms)
                flag = True

win32***以外をあまり使いたくなかったので、かなり原始的にキーイベントを取得しています。

使い方

実行後、alt+tでアクティブウィンドウが最上部に固定されます。
もう一度押すと(というか次の0.5秒も押し続けても)、固定が解除されます。
固定(解除)されると、ビープ音が鳴るので目安になります。

batファイルでも作って、デスクトップに放っておけばちょっとした時に便利です。

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