Gtkmm - 截图时始终保持相同的图像

时间:2015-08-02 16:42:16

标签: c++ c++11 screenshot gtk3 gtkmm

我有一个小型的c ++(c ++ 11)程序,可以截取整个屏幕,并在点击按钮时将其保存在文件中

这是我的代码:

#include <iostream>
#include <gtkmm.h>
using namespace Gtk;

class MainWindow : public Window
{
public:
    MainWindow(): m_button("Take Screen Shot")
    {

        add(m_button);

        m_button.signal_clicked().connect(std::bind(&MainWindow::on_mouse_clicked, this));
        m_button.show();
    }

    virtual ~MainWindow() {};
protected:
    void on_mouse_clicked()
    {
        auto root = Gdk::Window::get_default_root_window();
        int height = root->get_height();
        int width = root->get_width();
        auto pixels = Gdk::Pixbuf::create(root, 0, 0, width, height);
        pixels->save("s.png", "png");
    }

    Button m_button;
};



int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv);
    MainWindow mainapp;

    return app->run(mainapp);
}

问题是:我总是得到同样的形象!应用程序启动时的屏幕状态。我想总是得到屏幕的当前状态

1 个答案:

答案 0 :(得分:0)

遇到了同样的问题,但仅限于少数几台计算机。不知道,为什么会发生这种情况,但似乎是gtk和/或显示驱动程序错误(我有英特尔显示驱动程序的这个错误)。 在任何地方,以下解决方案对我有用,但只适用于本机x11:

Display *dpy = XOpenDisplay(NULL);
Window rootWnd = DefaultRootWindow(dpy);

XWindowAttributes wa;
XGetWindowAttributes(dpy, rootWnd, &wa);

XImage *rootImg = XGetImage(dpy, rootWnd, 0, 0, wa.width, wa.height, AllPlanes, ZPixmap);
const unsigned long mRed = rootImg->red_mask,
    mBlue = rootImg->blue_mask,
    mGreen = rootImg->green_mask
;
for(int y = 0; y < wa.height; y++)
{
    for(int x = 0; x < wa.width; x++)
    {
        const unsigned long bgrPixel = XGetPixel(rootImg, x, y);
        const unsigned char blue = bgrPixel & mBlue,
            green = (bgrPixel & mGreen) >> 8,
            red = (bgrPixel & mRed) >> 16,
            alpha = bgrPixel >> 24
        ;
        const unsigned long rgbPixel = red | (green << 8) | (blue << 16) | (alpha << 24);
        XPutPixel(rootImg, x, y, rgbPixel);
    }
}
Glib::RefPtr<Gdk::Pixbuf> img = Gdk::Pixbuf::create_from_data(
    (guint8 *)rootImg->data,
    Gdk::Colorspace::COLORSPACE_RGB,
    rootImg->bits_per_pixel == 32,
    8,
    rootImg->width,
    rootImg->height,
    rootImg->bytes_per_line
);
img->save("s.png", "png");

XDestroyImage(rootImg);
XCloseDisplay(dpy);

P.S。:请不要忘记Xlib可以与BGR一起使用,但是Gdk :: Pixbuf可以使用RGB模式。