[Mono-osx] Numbers only input validation code for using with NSTextField using Monobjc

Nick Ifloat ifloat at gmail.com
Mon Dec 15 01:02:46 EST 2008

Please help me with building an equivalent to the Numbers only input
validation code for using with NSTextField using Monobjc.

Case: I want the NSTextField to allow the user to input only numbers(0 to
9), '.' and '-' symbols.

Request: Well I am stuck. I am able to handle key press events in Windows
Forms and Gtk#. But I am new to Mac OS X and need your help with building an
equivalent method to handle key press events on Mac OS X using Monobjc. I am
providing my sample code of key press event handler using Windows Forms and
Gtk# bellow. (I have read about NSFormater, NSCell, NSView's keyDown method
- but I can't seem to find my way on doing the same using Monobjc!)

Provided: 1. Windows Forms & 2. Gtk# numbers only input sample code.

Need: Monobjc code for numbers only input validation sample code. 

//Windows Forms Code to handle KeyPressEvents

private void OnlyNumbers(KeyPressEventArgs e)
            char c = e.KeyChar;
            if (!(c >= '0' && c <= '9' || c == '.' || c == '-' || c == 8))
//8 is the keycode of the backspace key
                e.Handled = true;

//Then I am calling the method on the text fields KeyPress handler 

private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)

//End of Windows Forms Code

//Gtk# Code to handle/capture & kill Unwanted Keys

       private void OnlyNumbers(object o, Gtk.TextInsertedArgs
				Console.WriteLine("text : " + args.Text.ToString());
				int pos = ((Entry)o).Position;
				string c = ((Entry)o).GetChars(pos, pos+1);
				char d;
				Char.TryParse(c[0].ToString(), out d);
				if (!(d >= '0' && d <= '9' || d == '.' || d == '-'))
					((Entry)o).SelectRegion(pos, pos+1);
			catch (System.IndexOutOfRangeException e) {}

//Then I am passing the method to the textfields OnTextInserted event

protected virtual void txtNumber_OnTextInserted (object o,
Gtk.TextInsertedArgs args)
			OnlyNumbers(o, args);
//End of Gtk# code
View this message in context: http://www.nabble.com/Numbers-only-input-validation-code-for-using-with-NSTextField-using-Monobjc-tp21008715p21008715.html
Sent from the Mono - OSX mailing list archive at Nabble.com.

More information about the Mono-osx mailing list