Re: [gtkmm] Key Snooping / Key_Press_Event Howto?



Andrew E. Makeev wrote:
Jeff Gavin wrote:

I'm trying to validate an entry while the user types. I've read all the posts on entry validation and I still don't know an answer. I would like to create a entry that can validate a date while the user types it in, but to simplify things on the initial version, I decided to create an entry that only allows numbers to be typed in.

Keep in mind I come from a MS/VB background (I know, yech, ptooie, gross!).

From this experience, I have created entries that would intercept each keystroke and decide weather to accept them or not.

For example this VB code snip would not allow the "UserCode" field to accept certain characters. Changing the KeyAscii code to 0 prevents the entry from accepting the keystroke:

Private Sub txtUserCode_KeyPress(KeyAscii As Integer)
  ' Check for invalid character and exclude them.
If InStr(1, " ~`! #$%^&*()_+-={}[]\|:;<>,./?'""", Chr(KeyAscii)) > 0 Then
    KeyAscii = 0
  End If
End Sub

I cannot figure out how to do this with gtk+/gtkmm. The key_press_event seemed like an obvious candidate, but it only triggers when the user presses shift/esc/ctrl. Maybe this is not such a good name for this event if that's all it can do. Is there a way to make all the key presses to be passed to the callback? I'm sure someone has had to solve this type of problem before. How did you do it?

Best Regards,

Jeff

1. Try to read tutorial and API reference about signal/event processing.


I did try, but even now after knowing the answer, I cannot find it in the documentation. Where would I find this particular answer?

2. You have to connect to signal with parameter after=false set, like this:

<widget>.signal_key_press_event ().connect (SigC::slot (<callback>), false);

Thank you so much! I knew that I must be missing something fundamental like this! Here is how to register for a key_press_event (note that you must place false at the end):

my_entry->signal_key_press_event().connect(SigC::slot(*this,my_class::on_my_entry_key_press_event),false);

Then the callback function would look something like this:

// my_entry only allows digits 0..9 to be typed in.
// All other keystrokes are ignored.
bool my_class::on_my_entry_key_press_event (GdkEventKey* event)
{
	const static Glib::ustring s = "0123456789";
 	return (gint(s.find(event->string)) == -1);
}



then your callback would be called before Gtk+ keypress event handling.
Keep in mind you could stop event processing just with return value = true.


Again thanks!

Jeff




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]