This question has probably been asked and answered a million times on every conceivable programming forum. Every answer provided has the distinction of being unique to the stated requirements.
Since you are using a MaskedTextBox
, you have additional validation features available to you and do not really need to handle keypresses. You can simply set the Mask property to something like "L" (character required) or "?" (optional characters). In order to show feedback to the user that the input is not acceptable, you can use the BeepOnError
property or add a Tooltip to show the error message. This feedback mechanism should be implemented in the MaskedInputRejected
event handler.
The MaskedTextBox
control offers a ValidatingType
property to check input that passes the requirements of the Mask, but may not be the correct datatype. The TypeValidationCompleted
event is raised after this type validation and you can handle it to determine results.
If you still need to handle keypress events, then read on...!
The method I would recommend in your case is that instead of handling the KeyDown
event (you ostensibly do not need advanced key handling capability) or using a Regex to match input (frankly, overkill), I would simply use the built-in properties of the Char structure.
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Char pressedKey = e.KeyChar;
if (Char.IsLetter(pressedKey) || Char.IsSeparator(pressedKey) || Char.IsPunctuation(pressedKey))
{
// Allow input.
e.Handled = false
}
else
// Stop the character from being entered into the control since not a letter, nor punctuation, nor a space.
e.Handled = true;
}
}
Note that this snippet allows you to handle punctutation and separator keys as well.
The code project article Creating a Tasktray Application gives a very simple explanation and example of creating an application that only ever exists in the System Tray.
Basically change the Application.Run(new Form1());
line in Program.cs
to instead start up a class that inherits from ApplicationContext
, and have the constructor for that class initialize a NotifyIcon
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomApplicationContext());
}
}
public class MyCustomApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
public MyCustomApplicationContext ()
{
// Initialize Tray Icon
trayIcon = new NotifyIcon()
{
Icon = Resources.AppIcon,
ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Exit", Exit)
}),
Visible = true
};
}
void Exit(object sender, EventArgs e)
{
// Hide tray icon, otherwise it will remain shown until user mouses over it
trayIcon.Visible = false;
Application.Exit();
}
}
Best Answer
Two options:
Use a
NumericUpDown
instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox:
You can remove the check for
'.'
(and the subsequent check for more than one'.'
) if your TextBox shouldn't allow decimal places. You could also add a check for'-'
if your TextBox should allow negative values.If you want to limit the user for number of digit, use:
textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits