Taking screenshot of a specific window - C++ / Qt

2019-01-14 13:54发布

问题:

In Qt, how do I take a screenshot of a specific window (i.e. suppose I had Notepad up and I wanted to take a screenshot of the window titled "Untitled - Notepad")? In their screenshot example code, they show how to take a screenshot of the entire desktop:

originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());

How would I get the winId() for a specific window (assuming I knew the window's title) in Qt?

Thanks

回答1:

I'm pretty sure that's platform-specific. winIds are HWNDs on Windows, so you could call FindWindow(NULL, "Untitled - Notepad") in the example you gave.



回答2:

For Qt the way you "take a screenshot of a specific window" is to:

/*------ Take a screenshot of a window ------*/
// window is a: QWidget *window;
originalPixmap = QPixmap::grabWidget(window); 


回答3:

Look at QDesktopWidget class. It's inherited from QWidget so there is literally no problem of taking screenshot:

QPixmap pm(QDesktopWidget::screenGeometry().size());
QDesktopWidget::screen().render(&pm); // pm now contains screenshot


回答4:

Have a look at Screenshot example

In short:

QScreen *screen = QGuiApplication::primaryScreen();
if (screen)
    QPixmap originalPixmap = screen->grabWindow(0);


回答5:

Also look at WindowFromPoint and EnumChildWindows. The latter could allow you to prompt the user to disambiguate if you had multiple windows with the same title.



回答6:

Although this has already been answered, just for the sake of completeness, I'll add to Trevor Boyd Smith's post (see above) a code-snippet example:

void MainWindow::on_myButton_GUI_Screeshot_clicked()
{
    QPixmap qPixMap = QPixmap::grabWidget(this);  // *this* is window pointer, the snippet     is in the mainwindow.cpp file

    QImage qImage = qPixMap.toImage();

    cv::Mat GUI_SCREENSHOT = cv::Mat(         qImage.height(),
                                              qImage.width(), CV_8UC4,
                                      (uchar*)qImage.bits(),
                                              qImage.bytesPerLine()  );

    cv::imshow("GUI_SCREENSHOT",GUI_SCREENSHOT);
}