当前位置: 技术问答>linux和unix
GTK+鼠标事件问题
来源: 互联网 发布时间:2017-01-04
本文导语: #include #include #define TEST_W 100 #define TEST_H 80 gboolean drag = FALSE; // 只在左键按下时拖动窗体 int nX = 0; int nY = 0; static gint button_press_event(GtkWidget * widget, GdkEventButton * event, gpointer dat...
#include
#include
#define TEST_W 100
#define TEST_H 80
gboolean drag = FALSE; // 只在左键按下时拖动窗体
int nX = 0;
int nY = 0;
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;
return TRUE;
}
static gint motion_notify_event(GtkWidget * widget, GdkEventButton * event,
gpointer data) // 鼠标移动事件
{
if (drag)
{
int x, y;
GtkWidget *window = (GtkWidget *) data;
gtk_window_get_position((GtkWindow *) window, &x, &y); // 取窗体绝对坐标
gtk_window_move((GtkWindow *) window, x + event->x - nX, //x是当前窗口的绝对坐标,event->x是鼠标相对窗口的x坐标, nX是鼠标按下时记录的坐标,这三个量都是不变的,,窗口怎么会移动呢????
y + event->y - nY);// 移动窗体
}
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_decorated(GTK_WINDOW(window), FALSE); // 去掉边框
gtk_widget_set_size_request(window, TEST_W, TEST_H);
gtk_widget_set_events(window, // 设置窗体获取鼠标事件
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(window), "button_press_event",
(GtkSignalFunc) button_press_event, window); // 加入事件回调
gtk_signal_connect(GTK_OBJECT(window), "motion_notify_event",
(GtkSignalFunc) motion_notify_event, window);
gtk_signal_connect(GTK_OBJECT(window), "button_release_event",
(GtkSignalFunc) button_release_event, window);
gtk_widget_show_all(window);
gtk_main();
return TRUE;
}
|
nX是鼠标按下时 相对于 你连接信号的控件的坐标,也就是鼠标相对于window的坐标,x + event->x - nX不等于零,所以移动了吧