def is_process_running(self):
try:
if win32gui.FindWindow(None, "Nox") or win32gui.FindWindow(None, "NoxPlayer"):
return True
except:
return False
python类FindWindow()的实例源码
def __init__(self, window_name=None, exe_file=None, exclude_border=True):
hwnd = 0
# first check window_name
if window_name is not None:
hwnd = win32gui.FindWindow(None, window_name)
if hwnd == 0:
def callback(h, extra):
if window_name in win32gui.GetWindowText(h):
extra.append(h)
return True
extra = []
win32gui.EnumWindows(callback, extra)
if extra: hwnd = extra[0]
if hwnd == 0:
raise WindowsAppNotFoundError("Windows Application <%s> not found!" % window_name)
# check exe_file by checking all processes current running.
elif exe_file is not None:
pid = find_process_id(exe_file)
if pid is not None:
def callback(h, extra):
if win32gui.IsWindowVisible(h) and win32gui.IsWindowEnabled(h):
_, p = win32process.GetWindowThreadProcessId(h)
if p == pid:
extra.append(h)
return True
return True
extra = []
win32gui.EnumWindows(callback, extra)
#TODO: get main window from all windows.
if extra: hwnd = extra[0]
if hwnd == 0:
raise WindowsAppNotFoundError("Windows Application <%s> is not running!" % exe_file)
# if window_name & exe_file both are None, use the screen.
if hwnd == 0:
hwnd = win32gui.GetDesktopWindow()
self.hwnd = hwnd
self.exclude_border = exclude_border
def find_window(self, class_name, window_name = None):
"""Pass a window class name & window name directly if known to get the window """
self._handle = win32gui.FindWindow(class_name, window_name)
def getwindow(Title="SpotifyMainWindow"):
window_id = win32gui.FindWindow(Title, None)
return window_id
def _get_aimp_window(self):
"""Find the AIMP window handler who provides the remote API calls endpoint.
:raises RuntimeError: The AIMP window cannot be found.
:rtype: None
"""
self._aimp_window = win32gui.FindWindow(AIMPRemoteAccessClass, None)
if not self._aimp_window:
raise RuntimeError('Unable to find the AIMP window. Are you sure it is running?')
def new_icon(hdesk,desktop_name):
""" Runs as a thread on each desktop to create a new tray icon and handle its messages """
global id
id=id+1
hdesk.SetThreadDesktop()
## apparently the threads can't use same hinst, so each needs its own window class
windowclassname='PythonDesktopManager'+desktop_name
wc = win32gui.WNDCLASS()
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = windowclassname
wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW | win32con.CS_GLOBALCLASS
wc.hCursor = win32gui.LoadCursor( 0, win32con.IDC_ARROW )
wc.hbrBackground = win32con.COLOR_WINDOW
wc.lpfnWndProc = icon_wndproc
windowclass = win32gui.RegisterClass(wc)
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
hwnd = win32gui.CreateWindow(windowclass, 'dm_'+desktop_name, win32con.WS_SYSMENU,
0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0, wc.hInstance, None)
win32gui.UpdateWindow(hwnd)
flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
notify_info = (hwnd, id, flags, win32con.WM_USER+20, hicon, 'Desktop Manager (%s)' %desktop_name)
window_info[hwnd]=notify_info
## wait for explorer to initialize system tray for new desktop
tray_found=0
while not tray_found:
try:
tray_found=win32gui.FindWindow("Shell_TrayWnd",None)
except win32gui.error:
traceback.print_exc
time.sleep(.5)
win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, notify_info)
win32gui.PumpMessages()
def QQ_SendTextWithAt(str):
os.system(qq_shortcut)
try_time = 0
while True:
time.sleep(0.5)
hwnd = win32gui.FindWindow(None, '??&??')
# hwnd = win32gui.FindWindow(None, 'OSVT?O?')
print('try_time = %d, hwnd = %d' % (try_time, hwnd))
if hwnd != 0:
break
elif try_time >= 60:
print ('SendTextToQQ Error.')
return
else:
try_time = try_time + 1
win32gui.SetForegroundWindow(hwnd)
QQ_PrintTextWithAt(str)
QQ_Enter()
# win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, ord('v'), 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYUP, ord('v'), 0)
#win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, None, 'aaa')
#win32gui.SetWindowText(hwnd, 'aaa')
#win32gui.ReplaceSel()
#win32gui.PostMessage(hwnd, win32con.WM_CHAR, '', 3)
# win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_CONTROL, 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, ord('V'), 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYUP, ord('V'), 0)
# win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_CONTROL, 0)
def QQ_checkTargetWindow():
window_name = '?0'
hwnd = win32gui.FindWindow(None, window_name)
if hwnd == 0:
return 0
else:
print "find window = " + window_name.decode('gbk')
return hwnd
def GetHWND(self, wname = None):
'''
Gets handle of window to view
wname: Title of window to find
Return: True on success; False on failure
'''
if wname is None:
self.hwnd = win32gui.GetDesktopWindow()
else:
self.hwnd = win32gui.FindWindow(None, wname)
if self.hwnd == 0:
self.hwnd = None
return False
self.l, self.t, self.r, self.b = win32gui.GetWindowRect(self.hwnd)
return True
def new_icon(hdesk,desktop_name):
""" Runs as a thread on each desktop to create a new tray icon and handle its messages """
global id
id=id+1
hdesk.SetThreadDesktop()
## apparently the threads can't use same hinst, so each needs its own window class
windowclassname='PythonDesktopManager'+desktop_name
wc = win32gui.WNDCLASS()
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = windowclassname
wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW | win32con.CS_GLOBALCLASS
wc.hCursor = win32gui.LoadCursor( 0, win32con.IDC_ARROW )
wc.hbrBackground = win32con.COLOR_WINDOW
wc.lpfnWndProc = icon_wndproc
windowclass = win32gui.RegisterClass(wc)
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
hwnd = win32gui.CreateWindow(windowclass, 'dm_'+desktop_name, win32con.WS_SYSMENU,
0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0, wc.hInstance, None)
win32gui.UpdateWindow(hwnd)
flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
notify_info = (hwnd, id, flags, win32con.WM_USER+20, hicon, 'Desktop Manager (%s)' %desktop_name)
window_info[hwnd]=notify_info
## wait for explorer to initialize system tray for new desktop
tray_found=0
while not tray_found:
try:
tray_found=win32gui.FindWindow("Shell_TrayWnd",None)
except win32gui.error:
traceback.print_exc
time.sleep(.5)
win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, notify_info)
win32gui.PumpMessages()
def __init__(self, ????Name, reSetSelfWindow=False):
# ?????????
if reSetSelfWindow:
???hwnd = win32gui.FindWindow("ConsoleWindowClass", r"D:\ProgramFiles\Anaconda3\python.exe")
win32gui.SetWindowPos(???hwnd, win32con.HWND_TOP, 0,370,800,350, win32con.SWP_SHOWWINDOW)
# ??????????
self.????hwnd = win32gui.FindWindow("ConsoleWindowClass", ????Name)
if not self.????hwnd:
raise RuntimeError('????"{}"???!'.format(????Name))
win32gui.SetWindowPos(self.????hwnd, win32con.HWND_TOP, 0,0,800,350, win32con.SWP_SHOWWINDOW)
# ??????
self.cmdFM = CmdFileMap()
def FindMainWindow():
win_caption = 'autoxd_frame'
hwnd = 0
for i in range(10):
if hwnd == 0:
hwnd = win32gui.FindWindow(None, win_caption)
if win32gui.IsWindowVisible(hwnd) == True:
break
hwnd = win32gui.FindWindowEx(0, hwnd , None, win_caption)
if win32gui.IsWindowVisible(hwnd) == True:
break
return hwnd
def getwindowtitle():
if sys.platform == "win32":
spotify = win32gui.FindWindow('SpotifyMainWindow', None)
windowname = win32gui.GetWindowText(spotify)
elif sys.platform == "darwin":
windowname = ''
try:
command = "osascript getCurrentSong.AppleScript"
windowname = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
except Exception:
pass
else:
windowname = ''
session = dbus.SessionBus()
spotifydbus = session.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotifyinterface = dbus.Interface(spotifydbus, "org.freedesktop.DBus.Properties")
metadata = spotifyinterface.Get("org.mpris.MediaPlayer2.Player", "Metadata")
try:
command = "xwininfo -tree -root"
windows = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
spotify = ''
for line in windows.splitlines():
if '("spotify" "Spotify")' in line:
if " - " in line:
spotify = line
break
if spotify == '':
windowname = 'Spotify'
except Exception:
pass
if windowname != 'Spotify':
windowname = "%s - %s" %(metadata['xesam:artist'][0], metadata['xesam:title'])
if "—" in windowname:
windowname = windowname.replace("—", "-")
if "Spotify - " in windowname:
windowname = windowname.strip("Spotify - ")
return(windowname)
def findTopWindow(wantedText=None, wantedClass=None):
"""
:param wantedText: ????
:param wantedClass: ????
:return: ?????????
"""
return win32gui.FindWindow(wantedClass, wantedText)
def GetWinByTitle(cls, clsname=None, win_title=None, is_foreground=True):
"""
FindWindow? ????
"""
whd = 0
if clsname and win_title:
whd=win32gui.FindWindow(clsname, win_title)
elif clsname:
whd=win32gui.FindWindow(clsname, None)
elif win_title:
whd=win32gui.FindWindow(None, win_title)
if whd and is_foreground == True:
cls.SetAsForegroundWindow(whd)
return whd
def find_window(self, class_name, window_name=None):
"""Pass a window class name & window name directly if known to get the window """
self._handle = win32gui.FindWindow(class_name, window_name)
def _has_login_window(self):
for title in [' - ????', ' - ???? - ????']:
self.login_hwnd = win32gui.FindWindow(None, title)
if self.login_hwnd != 0:
return True
return False
def __init__(self, title):
self.topmost = not self.is_desktop_on_foreground()
self.hwnd = win32gui.FindWindow(None, title)
def _return_focus_w32(self):
w32win = win32gui.FindWindow(None, KWARGS['parent_title'])
win32gui.SetForegroundWindow(w32win)
def taskbar():
if platform == 'win':
# example:
# right side x>0 y=0 (1474, 0, 1536, 864)
# left side x=0 y<R/2 ( 0, 0, 62, 864)
# top side x=0 y=0 ( 0, 0, 1536, 27)
# bot side x=0 y>R/2 ( 0, 837, 1536, 864)
# get resolution to get taskbar position
res = sys_resolution()
# get taskbar rectangle
handle = win32gui.FindWindow("Shell_traywnd", None)
left, top, right, bottom = win32gui.GetWindowRect(handle)
x = y = 0
width, height = res
if left:
pos = 'right'
x = left
width = right - left
elif right < res['y'] / 2.0:
pos = 'left'
width = right
elif right > res['y'] / 2.0 and not top:
pos = 'top'
height = bottom
elif right > res['y'] / 2.0 and top:
pos = 'bottom'
y = top
height = bottom - top
else:
x, y, width, height, pos = (0, 0, 0, 0, '')
return {
'x': x, 'y': y,
'width': width, 'height': height,
'pos': pos
}