拖一个文件到窗口的GtkEntry中,
然后文件路径会被显示在GtkEntry中,并且使用系统默认程序打开该文件。
源代码如下,如果有什么问题再问吧。
#include <gtk/gtk.h>
/* 必须有这个,不然on_drag_data_received会调用两次
* 具体为什么我也不清楚,暂时就用这个方法来屏蔽掉一次
*/
static gboolean on_drag_drop()
{
return TRUE;
}
static void on_drag_data_received(GtkWidget *widget,
GdkDragContext *context,
gint x,gint y,
GtkSelectionData *data,
guint info,
guint time,
gpointer user_data)
{
GdkAtom atom=gtk_selection_data_get_data_type(data);
if(gtk_targets_include_uri(&atom,1)){
gchar **uris=gtk_selection_data_get_uris(data);
gint i=0;
while(uris[i]!=NULL){
g_printf("%s\n",uris[i]);
i++;
}
gtk_entry_set_text(GTK_ENTRY(widget),uris[0]);
/* 使用默认程序打开 */
g_app_info_launch_default_for_uri(uris[0],NULL,NULL);
g_strfreev(uris);
}
gtk_drag_finish(context,TRUE,TRUE,time);
}
int main(int argc,char *argv[])
{
gtk_init(&argc,&argv);
GtkWidget *window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window),380,160);
g_signal_connect(G_OBJECT(window),"destroy",
G_CALLBACK(gtk_main_quit),NULL);
GtkWidget *entry=gtk_entry_new();
GtkTargetEntry targets={
"text/uri-list",
GTK_TARGET_OTHER_APP,
1
};
gtk_drag_dest_set(entry,
GTK_DEST_DEFAULT_DROP,
&targets,1,
GDK_ACTION_COPY);
g_signal_connect(G_OBJECT(entry),"drag-data-received",
G_CALLBACK(on_drag_data_received),NULL);
g_signal_connect(G_OBJECT(entry),"drag-drop",
G_CALLBACK(on_drag_drop),NULL);
gtk_container_add(GTK_CONTAINER(window),entry);
gtk_widget_show_all(window);
gtk_main();
return 0;
}