Skip to content

Instantly share code, notes, and snippets.

@angstyloop
Created March 7, 2023 06:21
Show Gist options
  • Save angstyloop/3a72029e88cbbb100a0d6b4a1f811317 to your computer and use it in GitHub Desktop.
Save angstyloop/3a72029e88cbbb100a0d6b4a1f811317 to your computer and use it in GitHub Desktop.
Open a native file chooser with GTK 3 if one is available.
/** file_chooser_native.c
*
* Open a native file chooser with GTK 3 if one is available.
*
* COMPILE
* gcc -Wall -o file_chooser_native file_chooser_native.c `pkg-config gtk+-3.0 --libs --cflags`
*
* EXAMPLE
* ./file_chooser_native
*/
#include <gtk/gtk.h>
static void on_response(GtkNativeDialog *chooser, int response) {
if (response == GTK_RESPONSE_ACCEPT) {
GFile *file = gtk_file_chooser_get_file(GTK_FILE_CHOOSER(chooser));
gchar* path = g_file_get_path(file);
puts(path);
g_free(path);
g_object_unref(file);
}
g_object_unref(chooser);
}
int main(int argc, char** argv) {
// Initialize GTK
gtk_init(&argc, &argv);
// Create the window
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// Create the FileChooser
GtkFileChooserNative *chooser =
gtk_file_chooser_native_new("Open File",
(GtkWindow*) window,
GTK_FILE_CHOOSER_ACTION_OPEN,
"_Open",
"_Cancel");
// Connect the "response" signal handler
g_signal_connect(chooser, "response", G_CALLBACK(on_response), NULL);
// Show the dialog
gtk_native_dialog_show(GTK_NATIVE_DIALOG(chooser));
// Start the GTK main loop
gtk_main();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment