Last active
July 31, 2021 17:31
-
-
Save VadokDev/491a68bede11dc89fb8df4a87117bccd to your computer and use it in GitHub Desktop.
Focus Sublime Text 4 window on Windows every 3 seconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding:utf-8 | |
# Window focus on Windows source code: https://blog.csdn.net/qq_32126137/article/details/82217630 | |
# Find PId by process name on Windows source code: https://kkamikoon.tistory.com/85 | |
# Usage: python focusSublimeText4.py (you need an open Sublime Text 4 window) | |
import time | |
import os | |
import win32gui,win32process,win32con,win32com.client | |
from ctypes import * | |
class setf(): | |
def __init__(self): | |
self.shell=win32com.client.Dispatch("WScript.Shell") | |
self.dll=CDLL("user32.dll") | |
def setfocus(self): | |
pid=self.get_pid_for_pname() | |
if pid: | |
hwnd = self.get_hwnds_for_pid(pid)[0] | |
self.shell.SendKeys('%') | |
self.dll.LockSetForegroundWindow(2) | |
if self.dll.IsIconic(hwnd): | |
win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0) | |
self.dll.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,0,0,win32con.SWP_NOSIZE|win32con.SWP_NOMOVE) | |
self.dll.SetForegroundWindow(hwnd) | |
self.dll.SetActiveWindow(hwnd) | |
def get_pid_for_pname(self): | |
from win32com.client import GetObject | |
WMI = GetObject('winmgmts:') | |
processes = WMI.InstancesOf('Win32_Process') | |
process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes] | |
pid = [x for x in process_list if x[1] == "sublime_text.exe" ][0][0] | |
return pid | |
def get_hwnds_for_pid(self,pid): | |
def callback (hwnd, hwnds): | |
if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd): | |
_,found_pid=win32process.GetWindowThreadProcessId(hwnd) | |
if found_pid==pid: | |
hwnds.append(hwnd) | |
return True | |
hwnds=[] | |
win32gui.EnumWindows(callback, hwnds) | |
print( hwnds) | |
return hwnds | |
if __name__ == '__main__': | |
sf=setf() | |
while True: | |
time.sleep(3) | |
try: | |
sf.setfocus() | |
except Exception as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment