Friday 14 August 2009

GTK - how to enumerate widgets

I had fun recently trying to figure-out the code that would allow me to enumerate through all available GTK Widgets, a little bit like the Windows EnumWindows function. This took me a while to figure out... mainly because of the terrible state of the GTK documentation. :)

Anyways, here is the bare bones of the solution; as you can see, it is actually really easy.

A couple of things to note:
  • - a GtkWindow can be treated as a GtkWidget...!
  • - if a GtkWindow has child widgets, then it must be of type GTK_CONTAINER

static void widgetEnumerate (int nDepth, GtkWidget *pGtkWidget)
{
printf ("%d: Got GtkWidget=%x\n", nDepth, pGtkWidget);

// If the GtkWidget in question is a also a container,
// then we can enumerate through its children!
if (GTK_IS_CONTAINER(pGtkWidget)
{
GtkContainer *pGtkContainer = GTK_CONTAINER(pGtkWidget);
GList *pGtkWindowList = gtk_container_get_children(pGtkContainer);

GList *pNode;
for (pNode = pGtkWindowList; pNode != NULL; pNode = pNode->next)
{
GtkWidget *pGtkWidget = GTK_WIDGET(pNode->data);
widgetEnumerate(nDepth+1, pGtkWidget);
}
}
}

void enumerateGtkWidgets(void)
{
GList *pGtkWindowList = gtk_window_list_toplevels();
GList *pNode;
for (pNode = pGtkWindowList; pNode != NULL; pNode = pNode->next)
{
GtkWindow *pGtkWindow = GTK_WINDOW(pNode->pData);
widgetEnumerate(1, GTK_WIDGET(pGtkWindow));
}
}

1 comment:

Volodymyr Shcherbyna said...

Very nice example. Thank you!

However this method enumerates only windows of the current process. I wonder, is there any way to enumerate all windows of all processes in GTK?

Thank you,
V.