The
Solution 1 to 4
given already are good and provide the functionality required to some extent.
But to validate the text being pasted I think the
WndProc
method explained here
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc.aspx[
^]
is to be handled and to allow the
copy, paste
etc from key board
KeyDown
event is to be handled.
The list of Windows Messages are given here
List Of Windows Messages[
^]
The text to be pasted is combined with the existing text and tested with
Regex
with pattern
"^\d*p?\d*$"
before being pasted.
Since,
WndProc
is a
protected
method, the
TextBox
is to
sub classed
to provide the desired functionality as shown below:
public class NumTextBox : TextBox {
protected override void WndProc(ref System.Windows.Forms.Message m)
{
try {
if (m.Msg !=0x302) {
base.WndProc(ref m);
return;
}
string modifiedText = Text + Clipboard.GetText();
if (Regex.IsMatch(modifiedText,@"^\d*p?\d*$",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)){
Text = modifiedText;
SelectionStart = Text.Length;
}
} catch {
}
}
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs args) {
if (args.Control || args.Alt)
return;
switch(args.KeyCode){
case Keys.End:
case Keys.Home:
case Keys.Left:
case Keys.Right:
case Keys.Back:
case Keys.Delete:
return;
}
if (!char.IsDigit((char)args.KeyData) &&
(args.KeyCode != Keys.P || (args.KeyCode == Keys.P
&& Text.ToLower().Contains("p")))){
args.SuppressKeyPress=true;
}
}
}