Home >Backend Development >Python Tutorial >How to Programmatically Retrieve the Active Window in Python?

How to Programmatically Retrieve the Active Window in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 16:11:02968browse

How to Programmatically Retrieve the Active Window in Python?

Getting the Active Window in Python

Problem: How can I access the active window on the screen using Python? This window could be the admin login interface of a router, for example.

Solution:

On Windows, you can use the Python for Windows extensions (pywin32) to obtain the active window. Here's how:

<code class="python"># Python 2
from win32gui import GetWindowText, GetForegroundWindow
print GetWindowText(GetForegroundWindow())</code>
<code class="python"># Python 3
from win32gui import GetWindowText, GetForegroundWindow
print(GetWindowText(GetForegroundWindow()))</code>

Example:

The code below prints the title of the active window on the screen:

<code class="python">import win32gui

window_handle = win32gui.GetForegroundWindow()
window_title = win32gui.GetWindowText(window_handle)
print(window_title)</code>

The above is the detailed content of How to Programmatically Retrieve the Active Window in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn