'Check if the console application has the focus

I'm working on a Python console app. I want to check if the focus is on the console of my application. I can assume my code will be executed on a Windows PC. At the moment I'm using this unsafe version:

import win32gui

# Before the execution starts, I assume the focus will be on the console
CURRENT_CONSOLE = win32gui.GetForegroundWindow()

...

# Check if the console has the focus
if win32gui.GetForegroundWindow() == CURRENT_CONSOLE:
   ...

The obvious problem is that the user can change the focus before the execution arrives to the row that defines CURRENT_CONSOLE.

There is another problem: If I'm debugging Visual Code with the integrated console, my method cannot tell whether the focus is on the console or somewhere else in the Visual Code window (for example on the code).



Solution 1:[1]

Try this:

import win32gui,win32process,os

focus_window_pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())[1]
current_process_pid = os.getppid()

print(focus_window_pid == current_process_pid )

win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())[1] will get the parent process pid, so we need to use os.getppid() to get the parent pid of python process.

But if you are using other method to run your python script(eg: vscode), this method may not work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cliffsu