2

Say I create a dialog with

dialog = gtk_message_dialog_new(_, _, _, GTK_BUTTONS_YES_NO, _)

and that I want to process the response differently depending on whether the user pressed "No" or "Yes".

I know I can link the "response" signal to a callback with

g_signal_connect_swapped (dialog, "response", G_CALLBACK (callback_function, NULL);

but how do I check whether the "Yes" button was pressed? Thank you very much for the help.

ptomato
  • 56,175
  • 13
  • 112
  • 165
user1764386
  • 5,311
  • 9
  • 29
  • 42

1 Answers1

2

Look at the documentation of the response signal. The prototype of your function should be:

void
user_function (GtkDialog *dialog,
               gint       response_id,
               gpointer   user_data)

For that, use g_signal_connect(), not g_signal_connect_swapped(). The latter is used only for connecting funcions with a non-matching prototype (a very bad idea from the GTK+ people, IMHO).

There, response_id will be the identifier of the button pressed, or GTK_RESPONSE_DELETE_EVENT if the message was dismissed.

In the case of a GtkMessageDialog, the button identifiers are values of the enumeration GtkResponseType (GTK_RESPONSE_YES and GTK_RESPONSE_NO for your code). If you use your own dialog and buttons, you can use other identifiers, although the standard ones are recommended if reasonable.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • Here's the reason for `g_signal_connect_swapped`: http://stackoverflow.com/questions/2171724/what-does-g-signal-connect-swapped-do – ptomato May 03 '14 at 19:55
  • @ptomato: I understand the reasons, but I feel uncomfortable binding a function to a signal with a non-matching interface. The answer you linked says _the second argument is ignored, because that's the way the C calling convention works_, but I'm not sure this is guaranteed by the language, and nevertheless I find it _hackish_ at best. – rodrigo May 04 '14 at 08:44
  • It's not guaranteed by the C standard, but I assure you, it is guaranteed on every platform that GTK is ported to, because otherwise GTK would crash and burn horribly. And that is pretty much every platform that matters nowadays. Call it hackish, but it's the only sane way to implement a signal/handler system in C. And you're already doing it every time you connect a signal (since the prototype of GCallback is `void (*callback)(void)`. I have another answer [here](http://stackoverflow.com/questions/22402597/22419961#22419961) with more explanation ;-) – ptomato May 04 '14 at 19:07
  • @ptomato: It isn't the same to cast a function pointer `callback` and then back to the proper function pointer type, than to cast it to an unrelated function pointer and use that to call the function. I agree that it works where it matters, of course, but I don't like it, so my programs will never call `g_signal_connect_swapped()`. (I use C++11 for Gtk+ programming so I can use lambdas for signals ;-P). – rodrigo May 04 '14 at 19:38