You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在GTK4(C语言)中获取用户鼠标指针坐标的方法咨询

GTK4+C 获取鼠标位置解决方案

1. 替代gdk_device_get_position的方案

GTK4中gdk_device_get_position已被移除,替代函数是gdk_device_get_position_double,可用于获取鼠标指针相对于指定GdkSurface的坐标。示例代码如下:

// 获取默认显示设备的主指针设备(通常为鼠标)
GdkDevice *device = gdk_seat_get_pointer(gdk_display_get_default_seat(gdk_display_get_default()));
// 获取目标widget对应的surface
GdkSurface *surface = gtk_widget_get_surface(my_widget);

gdouble x, y;
// 获取鼠标相对于surface的坐标
gdk_device_get_position_double(device, surface, &x, &y);
// 此时x、y即为鼠标在widget区域内的坐标

2. 从GtkEventControllerMotion的motion信号获取坐标

你已正确配置事件控制器,只需按照信号签名定义回调函数,即可直接接收x、y参数。示例代码:

// 回调函数需严格匹配信号签名
static void my_function(GtkEventControllerMotion *controller, gdouble x, gdouble y, gpointer user_data) {
    // 直接使用x、y参数,比如打印坐标
    g_print("鼠标位置:x=%.2f, y=%.2f\n", x, y);
}

// 绑定信号时传入正确的函数指针
g_signal_connect(my_controller, "motion", G_CALLBACK(my_function), NULL);

注:此处的x、y是鼠标相对于目标widget左上角的像素坐标。

内容的提问来源于stack exchange,提问作者Oliver Cox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 23:50:53