【GTK】GTK之任意拖动窗口中的按钮

,任意拖动窗口中的按钮

源码:

#include <gtk/gtk.h>
GtkWidget *window;
GtkWidget *fixed;
GtkWidget *button;
gboolean drag = FALSE;   // 只在左键按下时拖动窗体

gint nX = 0;
gint nY = 0;

void destroy(GtkWidget *widget, gpointer *data)
{
    gtk_main_quit();
}

static gint button_press_event(GtkWidget * widget,GdkEventButton * event, gpointer data)
{    
      if (event->button == 1)       // 判断是否左键按下
        {
                 drag = TRUE;
                 nX = event->x;  // 取得鼠标相对于窗口的位置
                 nY = event->y;
        }

        return TRUE;

}
static gint button_release_event(GtkWidget * widget, GdkEventButton * event,gpointer data)         // 鼠标抬起事件
{

   
        if (event->button == 1)//第二次按下鼠标左键
            drag = FALSE;
     
   // gtk_fixed_move(GTK_FIXED(fixed),button,event->x,event->y);/*移动按纽*/
    return TRUE;

}



static gint motion_notify_event(GtkWidget * widget, GdkEventButton * event,gpointer data)  // 鼠标移动事件
{
     
       if (drag)
        { 
             //gint x, y;
             //GtkWidget *window = (GtkWidget *) data;
             //gtk_window_get_position((GtkWindow *)window, &x, &y);  // 取窗体绝对坐标
       
             gtk_fixed_move(GTK_FIXED(fixed),button,widget->allocation.x + event->x - nX,widget->allocation.x + event->y - nY);/*移动按纽*/
            // g_print("x=%d;y=%d\n",x + event->x - nX,y + event->y - nY);
             //gtk_fixed_move(GTK_FIXED(fixed),button,event->x , event->y);/*移动按纽*/
            //gtk_window_move((GtkWindow *) window, x + event->x - nX, y + event->y - nY);// 移动窗体
        }

        return TRUE;

}

int main(int argc, char *argv[])
{
    
    gtk_init(&argc,&argv);//初始化
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_signal_connect (GTK_OBJECT (window), "destroy",(GtkSignalFunc) destroy, NULL);
    gtk_window_set_title (GTK_WINDOW (window), "button_drag");
    //gtk_window_fullscreen(GTK_WINDOW(window));
    

    fixed = gtk_fixed_new();//函数用于创建新的固定容器
    gtk_container_add(GTK_CONTAINER(window), fixed);
   
    button=gtk_button_new_with_label("Button"); /*创建带标号的按钮*/
    //gtk_container_add(GTK_CONTAINER(window),button); /*把按钮加入窗体*/
    gtk_fixed_put(GTK_FIXED(fixed), button, 50, 50);//函数将widget放在fixed的由x和y指定的位置。
    gtk_widget_set_size_request(button, 80, 35);

    // 设置按钮获取鼠标事件
    gtk_widget_set_events(button, GDK_EXPOSURE_MASK | GDK_LEAVE_NOTIFY_MASK| GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK| GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
    gtk_signal_connect(GTK_OBJECT(button), "button_press_event",(GtkSignalFunc) button_press_event, window);       // 加入事件回调
    gtk_signal_connect(GTK_OBJECT(button), "button_release_event",(GtkSignalFunc) button_release_event, window);
    gtk_signal_connect(GTK_OBJECT(button), "motion_notify_event",(GtkSignalFunc) motion_notify_event, window);

    gtk_widget_show_all(window);
    gtk_main ();
    return 0;
}


posted @ 2011-12-25 23:21  MXi4oyu  阅读(478)  评论(0编辑  收藏  举报