qwerty
qwerty

Reputation: 229

How to grab a desktop screenshot with PyQt?

Can I take a screenshot from desktop or any window with PyQt? How to handle keyPressEvent on desktop?

Thanks.

Upvotes: 2

Views: 5248

Answers (3)

Big bubble
Big bubble

Reputation: 11

search the title items which you want

import win32gui
hwnd_title = dict()
def get_all_hwnd(hwnd,mouse):
  if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
    hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})

win32gui.EnumWindows(get_all_hwnd, 0)
 
for h,t in hwnd_title.items():
  if t is not "":
    print(h, t)

then use the title to screenshot

  from PyQt5.QtWidgets import QApplication
  from PyQt5.QtGui import *
  import win32gui
  import sys

  hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe')
  app = QApplication(sys.argv)
  screen = QApplication.primaryScreen()
  img = screen.grabWindow(hwnd).toImage()
  img.save("screenshot.jpg")

Upvotes: 1

user1767754
user1767754

Reputation: 25094

To get the App-Window use:

ex = Ui_MainWindow() #The class wher you call self.show()
QPixmap.grabWidget(ex).save('screenshot.jpg', 'jpg')

Upvotes: 0

Tommy Brunn
Tommy Brunn

Reputation: 2562

Example of how to take a screenshot of the desktop:

import sys
from PyQt4.QtGui import QPixmap, QApplication

app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('screenshot.jpg', 'jpg')

If you want to take a screenshot of a specific window, replace QApplication.desktop() with the widget you want to take a screenshot of.

Upvotes: 8

Related Questions