Find out which window the user is currently looking at with Python

Asked 2 years ago, Updated 2 years ago, 111 views

I'm making a keylogging program with Python for learning purposes.

I've already finished hooking up the keyboard to get the input value, but I can't even get the function or module I need to get the name of the window that the user is currently looking at, or the information I need to google to write this code.

What should I do?

python keylogger window

2022-09-22 08:29

2 Answers

While you are connected to Windows, I will upload a simple sample.

import time, ctypes

time.sleep(3) # Intentionally stops for 3 seconds to activate the window where you want to get the title. 

lib = ctypes.windll.LoadLibrary('user32.dll')
handle = lib.GetForegroundWindow() #Handled Active Window
buffer = ctypes.create_unicode_buffer(255) #Buffer to store the title
lib.GetWindowTextW(handle, buffer, ctypes.sizeof(buffer)) # Save Title to Buffer

print(buffer.value) # Buffer output


2022-09-22 08:29

You can get the handle with the GetForegroundWindow function, which is Windows api, and you can get the title with the GetWindowText function.

You can refer to the document below.

https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getforegroundwindow

https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw

Of course, you have to call Windows api, so Python can use ctypes to handle user32.dll or use pywin32.


2022-09-22 08:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.