Worms4Editor/W4Gui/Components/GenericUpDown.cs

108 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Media;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace W4Gui.Components
{
public abstract class GenericUpDown<T> : UpDownBase where T : IIncrementOperators<T>, IDecrementOperators<T>, IMinMaxValue<T>
{
internal virtual string allowedChars
{
get
{
return "-";
}
}
internal abstract string formatText(T val);
internal abstract T parseValue(string val);
private T value;
private bool updating = false;
public T Value
{
get
{
if (UserEdit) ValidateEditText();
return value;
}
set
{
this.value = value;
UpdateEditText();
}
}
public override void DownButton()
{
try
{
Value--;
}
catch (OverflowException) { Value = T.MinValue; };
}
public override void UpButton()
{
try
{
Value++;
}
catch (OverflowException) { Value = T.MaxValue; };
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
ValidateEditText();
}
protected override void UpdateEditText()
{
if (updating) return;
updating = true;
this.Text = formatText(value);
updating = false;
}
protected override void OnTextBoxKeyPress(object? source, KeyPressEventArgs e)
{
base.OnTextBoxKeyPress(source, e);
if (!e.Handled)
{
if (char.IsDigit(e.KeyChar)) return;
else if (allowedChars.Contains(e.KeyChar.ToString().ToLower().First())) return;
else if (e.KeyChar == '\b') return;
else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) return;
e.Handled = true;
SystemSounds.Beep.Play();
}
}
protected override void ValidateEditText()
{
try
{
value = parseValue(this.Text);
}
catch (OverflowException)
{
if (Text.StartsWith("-")) Value = T.MinValue;
else value = T.MaxValue;
}
catch { }
UpdateEditText();
UserEdit = false;
}
}
}