Introduction
In this example, we create a single button and an event handler to respond to mouse clicks on the button. When the Click Me button is clicked, the button_clicked function will send a message to the command line that says “Button was clicked.” Also, the destroyapp function allows the window to close correctly when the X button on the title bar is clicked.
Screenshot
Source Code
/*
*File name: button.c
*/#include
#include/*– This function allows the program to exit properly when the window is closed –*/
gint destroyapp (GtkWidget *widget, gpointer gdata)
{
g_print (“Quitting…\n”);
gtk_main_quit();
return (FALSE);
}/*– This function responds to the mouse click on the button –*/
void button_clicked(GtkWidget *widget, gpointer gdata)
{
g_print(“Button was clicked.\n”);
}int main (int argc, char *argv[])
{
/*– Declare the GTK Widgets used in the program –*/
GtkWidget *window;
GtkWidget *button;/*– Initialize GTK –*/
gtk_init (&argc, &argv);/*– Create the new window –*/
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);/*– Create a button –*/
button = gtk_button_new_with_label(“Click Me”);/*– Connect the window to the destroyapp function –*/
gtk_signal_connect(GTK_OBJECT(window), “delete_event”, GTK_SIGNAL_FUNC(destroyapp), NULL);/*– Connect the button to the button_was_clicked function –*/
gtk_signal_connect(GTK_OBJECT(button), “clicked”, GTK_SIGNAL_FUNC(button_clicked), NULL);/*– Add the button to the window –*/
gtk_container_add(GTK_CONTAINER (window), button);/*– Add a border to the window to give the button a little room –*/
gtk_container_border_width (GTK_CONTAINER (window), 15);/*– Display the widgets –*/
gtk_widget_show(button);
gtk_widget_show(window);/*– Start the GTK event loop –*/
gtk_main();/*– Return 0 if exit is successful –*/
return 0;
}
Compile the Source Code
gcc -Wall -g button.c -o button `gtk-config –cflags` `gtk-config –libs`
Execute the Program
./button






