保持终端焦点 [英] Keeping the terminal in focus

查看:299
本文介绍了保持终端焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用selenium来自动执行网页操作的python脚本,将焦点从需要用户输入的终端上移开。

I have a python script which uses selenium to automate web page, drawing focus away from the terminal where user input is required.

python中是否总有焦点切换回到终端,以编程方式进行?

如果重要的话,我将在Windows 7的Windows命令提示符中运行我的程序,但是跨平台的答案将是最有用的

I will be running my program in the Windows Command Prompt on Windows 7, if it matters, but a cross platform answer would be most useful.

查看 pywin32 包对于win32 API的绑定,我有以下内容:

Looking at the pywin32 package bindings for the win32 API I have the following:

import win32console
import win32gui
from selenium import webdriver as wd

d = wd.Firefox()
win32gui.SetFocus(win32console.GetConsoleWindow())
win32gui.FlashWindow(win32console.GetConsoleWindow(), False)
input('Should have focus: ')

SetFocus 导致错误 pywintypes.error:(5, SetFocus,访问被拒绝。)由于Microsoft删除了

SetFocus causes the error pywintypes.error: (5, 'SetFocus', 'Access is denied.') due to Microsoft removing the ability to take focus from another application.

FlashWindow 似乎什么也没做。

推荐答案

这是我想出的方法,似乎在起作用。

Here is what I came up with that seems to be working.

class WindowManager:
    def __init__(self):
        self._handle = None

    def _window_enum_callback( self, hwnd, wildcard ):
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd

    #CASE SENSITIVE
    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self):
        win32gui.ShowWindow(self._handle, win32con.SW_RESTORE)
        win32gui.SetWindowPos(self._handle,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)  
        win32gui.SetWindowPos(self._handle,win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)  
        win32gui.SetWindowPos(self._handle,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        win32gui.SetForegroundWindow(self._handle)

    def find_and_set(self, search):
        self.find_window_wildcard(search)
        self.set_foreground()

然后找到一个窗口并将其激活,您可以...

Then to find a window and make it active you can...

w = WindowManager()
w.find_and_set(".*cmd.exe*")

这在python 2.7中,这也是一些链接我发现可以解释为什么您必须经历很多麻烦才能切换活动窗口。

This is in python 2.7, also here are some links I found to explain why you have to go through so much trouble to switch active windows.

无法指定的程序> win32gui.SetActiveWindow()错误:找不到特定的程序

Windows 7: how to bring a window to the front no matter what other window has focus?

这篇关于保持终端焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆