gdk_screen_get_default() returns 空

gdk_screen_get_default() returns null

请帮助这个初学者获取 gdk 屏幕属性的程序。我有一个小的 C++ 程序来找出连接的显示单元。我在 Linux Debian 上使用 C++。 gdk_screen_get_default() return Screen 不反对。如果我不检查屏幕对象,则会发生以下错误。

Error (process:8023): Gdk-CRITICAL **: gdk_screen_get_monitor_geometry: assertion 'GDK_IS_SCREEN (screen)' failed

我浏览了相关帖子并参考了 this 以下代码片段。

感谢您的帮助。解决此问题的任何 pointers/guidelines 都会有所帮助。

我连接了一台显示器,显示设置为

$ echo $XDG_CURRENT_DESKTOP
GNOME

$ echo $DISPLAY
:0

代码

    #include <gdk/gdk.h>
    #include <iostream>

    /*
    GTK version 3.14.5
    g++ getScreenInfo.cpp -o getScreenInfo `pkg-config gtk+-3.0 --cflags --libs`
    */

    int main()
    {
       GdkScreen *screen;
       screen = gdk_screen_get_default();           
       int num_monitors;
       int i;

       if (screen)
       {
          num_monitors = gdk_screen_get_n_monitors(screen);

          for (i = 0; i < num_monitors; i++)
          {
              GdkRectangle rect;
              gdk_screen_get_monitor_geometry (screen, i, &rect);
              std::cout << "monitor " << i << ": coordinates (" << rect.x << ","
              <<  rect.y << ", size (" << rect.width << "," << rect.height << ")"
              << std::endl;
           }
       }else
       {
            std::cout << "Couldn't obtain default screen object" << std::endl;
        }
    }

2017 年 4 月 27 日编辑:已解决

  #include <iostream>
  #include <gdk/gdk.h>
  #include <gtk/gtk.h>

  /*
  GTK version 3.14.5

  To compile:

  g++ getScreenInfo.cpp -o getScreenInfo `pkg-config gtk+-3.0 --cflags --libs`

  */

  int main(int argc, char *argv[])
  {
    gtk_init(&argc, &argv);

    GdkScreen *screen = gdk_screen_get_default();



    int num_monitors;
    int i;

    if (screen)
    {
        num_monitors = gdk_screen_get_n_monitors(screen);

        for (i = 0; i < num_monitors; i++)
        {
            GdkRectangle rect;
            gdk_screen_get_monitor_geometry (screen, i, &rect);
            std::cout << "monitor " << i << ": offsets (" << rect.x << ","
            <<  rect.y << ", size (" << rect.width << "," << rect.height << ")"
            << std::endl;
        }
    }
    else
    {
        std::cout << "Couldn't obtain default screen object" << std::endl;
    }

    // To query primary display properties 

    guint monitor = gdk_screen_get_primary_monitor(screen);
    GdkRectangle screen_geometry = { 0, 0, 0, 0 };
    gdk_screen_get_monitor_geometry(screen, monitor, &screen_geometry);
    std::cout << screen_geometry.x << std::endl;
    std::cout << screen_geometry.y  << std::endl;
    std::cout << screen_geometry.width  << std::endl;
    std::cout << screen_geometry.height << std::endl;
  }

回答我自己的问题。

终于想出了解决办法。 gtk_init( ) 在获取屏幕之前丢失。添加了 gtk/gtk.h 的相应包含,现在代码看起来像

int main(int argc, char *argv[]) 
{ 
   gtk_init(&argc, &argv);                 // <---- added this

   GdkScreen *screen = gdk_screen_get_default(); 

   : 
   followed by rest of the code shared in the problem description above.