An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.
The system automatically enables calls to SetForegroundWindow if the user presses the ALT key or takes some action that causes the system itself to change the foreground window (for example, clicking a background window).
下面是一个最简单的解决方案,因为我们能够模拟Alt按:
import tkinter as tk
import ctypes
# store some stuff for win api interaction
set_to_foreground = ctypes.windll.user32.SetForegroundWindow
keybd_event = ctypes.windll.user32.keybd_event
alt_key = 0x12
extended_key = 0x0001
key_up = 0x0002
def steal_focus():
keybd_event(alt_key, 0, extended_key | 0, 0)
set_to_foreground(window.winfo_id())
keybd_event(alt_key, 0, extended_key | key_up, 0)
entry.focus_set()
window = tk.Tk()
entry = tk.Entry(window)
entry.pack()
# after 2 seconds focus will be stolen
window.after(2000, steal_focus)
window.mainloop()
如果
focus_force()
不工作,可以尝试执行:基本上是一样的,只是写得不同。我刚刚在Python2.7上测试过。
root.focus_force()
不起作用,但上面的方法起作用了。Windows的解决方案有点棘手——你不能仅仅从另一个窗口窃取焦点,你应该以某种方式将你的应用程序移到前台。 但首先,我建议你消耗一个littlebit of windows theory,所以我们可以确认,这是我们想要达到的。
正如我在comment中提到的,这是一个使用SetForegroundWindow函数的好机会(还可以检查限制!)。但考虑到这些东西是一个廉价的黑客,因为用户“拥有”前台,Windows会不惜一切代价阻止你:
另外,请检查this页上的备注:
下面是一个最简单的解决方案,因为我们能够模拟
Alt
按:一些链接和示例:
不知道你面临什么问题。但下面是对我非常有用的示例代码。
这是在Windows10上使用最新的Python3.6测试的。
结果是在运行程序之后,我可以开始输入,然后他输入到第一个文本框
相关问题 更多 >
编程相关推荐