Here is a custom NumericUpDown
- Has a list property for disallowed values
- Prevents copy from Windows Clipboard
- Several overrides to prevent disallowed values
- Prevent beep on pressing enter key
- Property to get decimal Value as int
- overrides for DownButton and UpButton refinements of KO
using System.ComponentModel;
namespace TODO;
public class SpecialNumericUpDown : NumericUpDown
{
public SpecialNumericUpDown()
{
TextAlign = HorizontalAlignment.Right;
DisallowValues = new List<decimal>();
}
[Browsable(false)] public int AsInteger => (int)Value;
public delegate void TriggerDelegate();
public event TriggerDelegate TriggerEvent;
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
e.Handled = true;
e.SuppressKeyPress = true;
TriggerEvent?.Invoke();
return;
}
base.OnKeyDown(e);
}
[Category("Custom")]
[Description("Values not permitted")]
public List<decimal> DisallowValues { get; set; }
[Browsable(false)]
public bool IsValid => DisallowValues.Contains(Value) == false;
protected override void OnKeyUp(KeyEventArgs e)
{
if (DisallowValues.Contains(Value))
{
Value++;
return;
}
base.OnKeyUp(e);
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
if (DisallowValues.Contains(Value))
{
Value++;
return;
}
base.OnMouseUp(mevent);
}
public override void DownButton()
{
base.DownButton();
if (DisallowValues.Contains(Value))
{
Value--;
}
}
public override void UpButton()
{
base.UpButton();
if (DisallowValues.Contains(Value))
{
Value++;
}
}
// code to prevent paste from clipboard
Handler _handler;
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
_handler = new Handler(Controls[1]);
}
protected override void Dispose(bool disposing)
{
if (_handler != null)
_handler.DestroyHandle();
base.Dispose(disposing);
}
private class Handler : NativeWindow
{
Control _control;
public Handler(Control control)
{
_control = control;
AssignHandle(_control.Handle);
}
protected override void WndProc(ref Message m)
{
if (m.Msg != 0x0302 /*WM_PASTE*/)
{
base.WndProc(ref m);
}
else
{
System.Media.SystemSounds.Beep.Play();
}
}
}
}
Disallow property in form designer