Created
November 4, 2010 21:30
-
-
Save bert/663226 to your computer and use it in GitHub Desktop.
Validate input to a GtkEntry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* If you want to validate the text that a user enters into a GtkEntry widget | |
* you can attach to the "insert_text" signal of the entry, and modify the text | |
* within the callback function.\n | |
* The example below forces all characters to uppercase, and limits the range of | |
* characters to A-Z.\n | |
* Note that the entry is cast to an object of type GtkEditable, from which | |
* GtkEntry is derived. | |
*/ | |
#include <ctype.h> | |
#include <gtk/gtk.h> | |
void | |
insert_text_handler | |
( | |
GtkEntry *entry, | |
const gchar *text, | |
gint length, | |
gint *position, | |
gpointer data | |
) | |
{ | |
GtkEditable *editable = GTK_EDITABLE (entry); | |
int i, count=0; | |
gchar *result = g_new (gchar, length); | |
for (i=0; i < length; i++) | |
{ | |
if (!isalpha (text[i])) | |
continue; | |
result[count++] = islower (text[i]) ? toupper (text[i]) : text[i]; | |
} | |
if (count > 0) | |
{ | |
g_signal_handlers_block_by_func | |
( | |
G_OBJECT (editable), | |
G_CALLBACK (insert_text_handler), | |
data | |
); | |
gtk_editable_insert_text | |
( | |
editable, | |
result, | |
count, | |
position | |
); | |
g_signal_handlers_unblock_by_func | |
( | |
G_OBJECT (editable), | |
G_CALLBACK (insert_text_handler), | |
data | |
); | |
} | |
g_signal_stop_emission_by_name | |
( | |
G_OBJECT (editable), | |
"insert_text" | |
); | |
g_free (result); | |
} | |
int | |
main | |
( | |
int argc, | |
char *argv[] | |
) | |
{ | |
GtkWidget *window; | |
GtkWidget *entry; | |
gtk_init (&argc, &argv); | |
/* create a new window */ | |
window = gtk_window_new (GTK_WINDOW_TOPLEVEL); | |
gtk_window_set_title (GTK_WINDOW (window), "GTK Entry"); | |
g_signal_connect | |
( | |
G_OBJECT (window), | |
"destroy", | |
G_CALLBACK (gtk_main_quit), | |
NULL | |
); | |
entry = gtk_entry_new (); | |
g_signal_connect | |
( | |
G_OBJECT(entry), | |
"insert_text", | |
G_CALLBACK(insert_text_handler), | |
NULL | |
); | |
gtk_container_add (GTK_CONTAINER (window), entry); | |
gtk_widget_show (entry); | |
gtk_widget_show (window); | |
gtk_main (); | |
return (0); | |
} | |
/* EOF */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment