Worms4Editor/W4Gui/IntNumericUpDown.cs

101 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
namespace W4Gui
{
public class IntNumericUpDown : UpDownBase
{
private int value = 0;
private bool updating = false;
public int Value
{
get
{
if (this.UserEdit) ValidateEditText();
return this.value;
}
set
{
this.value = value;
UpdateEditText();
}
}
public override void DownButton()
{
try
{
this.Value--;
}
catch (OverflowException) { this.Value = Int32.MinValue; };
}
public override void UpButton()
{
try
{
this.Value++;
}
catch (Exception) { this.Value = Int32.MaxValue; };
}
protected override void UpdateEditText()
{
if (this.updating) return;
this.updating = true;
this.Text = this.Value.ToString();
this.updating = false;
}
protected override void OnTextBoxKeyPress(object? source, KeyPressEventArgs e)
{
base.OnTextBoxKeyPress(source, e);
if (Char.IsDigit(e.KeyChar)) return;
else if ("-\b".Contains(e.KeyChar.ToString().ToLower().First())) return;
else if ((Control.ModifierKeys & (Keys.Control | Keys.Alt)) != 0) return;
e.Handled = true;
SystemSounds.Beep.Play();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
if (UserEdit)
{
UpdateEditText();
}
}
protected override void ValidateEditText()
{
try
{
this.value = Int32.Parse(this.Text);
UpdateEditText();
}
catch (OverflowException ex)
{
if(this.Text.StartsWith("-")) this.Value = Int32.MinValue;
else this.Value = Int32.MaxValue;
}
catch
{
UpdateEditText();
}
finally
{
UserEdit = false;
};
}
}
}