How to Record a Specific Window in Python

Learn how to record a specific opened window in your Windows machine using pyautogui and pygetwindow libraries in Python.
  · 4 min read · Updated dec 2021 · Python for Multimedia

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

In the recording screen tutorial, we have built a working Python code for recording the entire screen using OpenCV and pyautogui libraries. In this tutorial, you will learn how to record a specific window on your Windows machine using the pygetwindow library and the mentioned libraries.

pygetwindow will provide us with the location, width, and height of the window of our choice, we simply provide a string to the getWindowsWithTitle() method, and it'll return a list of matched windows.

Unfortunately, the code of this tutorial will only work on Windows, as pygetwindow is a library for Windows environment for now.

A lot of the code of this tutorial is explained in the original screen recorder tutorial, make sure to open it up for detailed information.

To get started, let's install the required libraries:

$ pip install numpy opencv-python pyautogui pygetwindow

Open up a new Python file and import the libraries:

import cv2
import numpy as np
import pyautogui
import pygetwindow as gw
import sys

We are going to get the window name from the command-line arguments:

# the window name, e.g "notepad", "Chrome", etc.
window_name = sys.argv[1]

Defining some of our variables:

# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# frames per second
fps = 12.0
# the time you want to record in seconds
record_seconds = 10

We want to use an FPS of 12, and record for 10 seconds. Feel free to change record_seconds on your needs. fourcc is the video codec library. Again, check the screen recorder tutorial for detailed info.

Next, we search for the specified window:

# search for the window, getting the first matched window with the title
w = gw.getWindowsWithTitle(window_name)[0]
# activate the window
w.activate()

To search for a window by string, we use the getWindowWithTitle() method, which accepts a string and returns a list of matched windows, we simply take the first one. We use the activate() method to show and focus the window, so if it's minimized, it will be shown on the screen immediately after calling this method.

Finally, the rest of the code is the same as the recording screen tutorial:

# create the video write object
out = cv2.VideoWriter("output.avi", fourcc, fps, tuple(w.size))

for i in range(int(record_seconds * fps)):
    # make a screenshot
    img = pyautogui.screenshot(region=(w.left, w.top, w.width, w.height))
    # convert these pixels to a proper numpy array to work with OpenCV
    frame = np.array(img)
    # convert colors from BGR to RGB
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # write the frame
    out.write(frame)
    # show the frame
    cv2.imshow("screenshot", frame)
    # if the user clicks q, it exits
    if cv2.waitKey(1) == ord("q"):
        break

# make sure everything is closed when exited
cv2.destroyAllWindows()
out.release()

This time, we specify the size of the screen as the window size by passing tuple(w.size). We also specify the region keyword argument in the pyautogui.screenshot() method, the region is a tuple of left position, the top position, width, and height of the window, we simply get those from our window we extracted earlier.

Trying to record notepad for 10 seconds:

$ python record_specific_window.py notepad

This will activate the notepad window (if it is open in your system of course, otherwise it'll raise an IndexError) and start recording for the specified seconds. Here is the output video:

 

The nice thing about this is that the window location automatically changes when you move the window during the recording. However, do not change the size of the window when recording, as it'll corrupt the output video file.

Conclusion

Alright, I think this tutorial will certainly help you if you wanted to record a window in your Windows environment and not the whole screen.

It is worth mentioning that this method only works on the primary screen, if the window happens to be in other monitors, it will simply be recorded as a black screen, so you have to move it into the primary screen of your machine.

You can also comment out the cv2.imshow() method in the loop to remove showing the record in real-time.

Check the full code here.

Learn also: How to Play and Record Audio in Python

Happy coding ♥

Save time and energy with our Python Code Generator. Why start from scratch when you can generate? Give it a try!

View Full Code Convert My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!