我有此代码:
#include <stdio.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
guint threadID = 0;
guint serial_counter = 0;
static gboolean
serial_data (gpointer user_data)
{
printf("hello\n");
printf("counter: %d\n", serial_counter);
serial_counter++;
return user_data;
}
static void
on_pressed (GtkButton* button, gpointer user_data)
{
if (user_data == 1)
{
threadID = g_timeout_add(250, serial_data, user_data);
}
else if (user_data == 0)
{
g_source_remove(threadID);
threadID = 0;
}
}
int
main (int argc, char *argv[])
{
GtkWidget *window;
gtk_init (&argc, &argv);
GtkWidget *stop_button;
GtkWidget *box;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "test.c");
box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
stop_button = gtk_button_new_with_label (_("Stop"));
gtk_box_pack_start (GTK_BOX (box), stop_button, FALSE, FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), box);
g_signal_connect (window, "button-press-event", G_CALLBACK (on_pressed), 1);
g_signal_connect (stop_button, "clicked", G_CALLBACK (on_pressed), 0);
g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_widget_show_all (window);
gtk_main ();
return 0;
}
可以使用以下哪个进行编译:
gcc prueba.c `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0` -o test
我只想在按下鼠标按钮(单击但不松开)时打印一条消息。可以通过修改此代码来实现吗? 目的是在当前窗口的任何部分按鼠标右键,并打印一条消息,直到释放该按钮。
答案 0 :(得分:1)
我不知道您在哪里声明了信号处理函数。根据{{3}}
,它看起来应该有所不同这是一个剥离的示例,在该示例中,我使用“按下”和“释放”事件来指示按钮状态,并根据状态来相应地处理“鼠标移动”事件。 您可以添加打印功能和计时器。
static gboolean on_mouse_button_event(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
if (event->button.button != 3) // right button
return FALSE;
if (event->button.type == GDK_BUTTON_PRESS)
{
if (!button_pressed)
{
button_pressed = TRUE;
// Start timer
}
}
else if (event->button.type == GDK_BUTTON_RELEASE)
{
if (button_pressed)
{
button_pressed = FALSE;
// Stop timer
}
}
return TRUE;
}
...
g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_mouse_button_event), NULL);
g_signal_connect(G_OBJECT(widget), "button-release-event", G_CALLBACK(on_mouse_button_event), NULL);