How to Make a GUI in C
- 1). Download and install GTK+, setting it up for use with your C compiler as indicated in the documentation. Open your IDE or text editor and begin a new project.
- 2). Include the GTK+ header files and begin your main() function. Create pointers for both the window and the button you'll place inside of it and initialize the GTK+ library with the gtk_init() function. This should look like the following:
#include <gtk/gtk.h>
int main(int argc, char *argv[] )
{
GtkWidget *window;
GtkWidget *button;
gtk_init(&argc, &argv); - 3). Create the data structures for the window and tell the program to close the window if it receives the "destroy" signal. Give the window a padding of 10 pixels around any widgets it contains and create such a widget, creating the data structures for a button labeled "Hello, World!" Cause the button to close the window when it receives the "clicked" signal. This should look like the following:
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
button = gtk_button_new_with_label("Hello, World");
g_signal_connect_swapped(button, "clicked", G_CALLBACK(gtk_widget_destroy), window); - 4). Place the button inside the window and display both of them on the screen. Call the gtk_main() function to wait for user input, going back into action when the user clicks the button or attempts to close the program. This should look like the following:
gtk_container_add(GTK_CONTAINER(window), button);
gtk_widget_show(button);
gtk_widget_show(window);
gtk_main();
return 0;
} - 5). Save your code as "helloworld.c" and compile it with the GTK+ libraries. This is done with the following command line using GCC --- consult your documentation if you use a different C compiler:
gcc -Wall -g helloworld.c -o helloworld `pkg-config --cflags --libs gtk+-2.0`