使用python截图记事本

2024-04-23 11:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用窗口句柄截图记事本的运行实例?我已经知道了如何在python对话框中成功地截屏一个小部件。我还想出了如何处理运行记事本窗口。我被困在试图捕捉屏幕截图的窗口使用处理。你知道吗

import os, sys
from PySide import QtGui, QtCore
import ctypes

class GuiCaptureWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(GuiCaptureWindow, self).__init__(parent)
        self.resize(250, 100)
        self.setWindowTitle('GUI Capture')

        # console
        self.ui_capture = QtGui.QPushButton('Capture')

        main_layout = QtGui.QGridLayout()
        main_layout.addWidget(self.ui_capture)

        main_widget = QtGui.QWidget()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

        # signals
        self.ui_capture.clicked.connect(self.capture)


    def getRelativeFrameGeometry(self, widget):
        g = widget.geometry()
        fg = widget.frameGeometry()
        return fg.translated(-g.left(),-g.top())


    def screenCaptureWidget(self, widget, filename, fileformat='.png'):
        rfg = self.getRelativeFrameGeometry(widget)
        pixmap =  QtGui.QPixmap.grabWindow(widget.winId(),
                                           rfg.left(), rfg.top(),
                                           rfg.width(), rfg.height())
        filepath = os.path.abspath(filename + fileformat)
        pixmap.save(filepath) 
        os.system("start " + filepath)

    def capture(self):
        self.collect_window_titles()
        self.screenCaptureWidget(self.ui_capture, 'test')


    def collect_window_titles(self):
        EnumWindows = ctypes.windll.user32.EnumWindows
        EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
        GetWindowText = ctypes.windll.user32.GetWindowTextW
        GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
        IsWindowVisible = ctypes.windll.user32.IsWindowVisible

        apps = []
        def foreach_window(hwnd, lParam):
            if IsWindowVisible(hwnd):
                length = GetWindowTextLength(hwnd)
                buff = ctypes.create_unicode_buffer(length + 1)
                GetWindowText(hwnd, buff, length + 1)
                if buff.value:
                    apps.append({'title': buff.value, 'handle': hwnd})
            return True
        EnumWindows(EnumWindowsProc(foreach_window), 0)

        for app in apps:
            print app
            if app['title'] == 'Untitled - Notepad':
                print 'CAPTURE'
                return


def main():
    app = QtGui.QApplication(sys.argv)
    ex = GuiCaptureWindow()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Tags: selfappuiifmaindefwidgetwindow