/
NumericalTextBox.cs
139 lines (124 loc) · 2.81 KB
/
NumericalTextBox.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// This file is part of Handbell Manager.
// Copyright Graham John 2009-2020. graham@changeringing.co.uk
//
// Handbell Manager is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Handbell Manager is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Handbell Manager. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace HandbellManager
{
class NumericalTextBox : TextBox
{
bool _fixingText;
int _selstart;
int _value;
string _text;
public NumericalTextBox()
{
FixText();
}
private void FixText()
{
if (_fixingText)
return;
_fixingText = true;
_selstart = SelectionStart;
_text = Text;
for (int i = 0; i < _text.Length; i++)
{
if (i == 0 && _text[i] == '-')
continue;
if (!Char.IsNumber(_text[i]))
{
_text = _text.Remove(i, 1);
if (i <= _selstart)
_selstart -= 1;
if (_selstart < 0)
_selstart = 0;
i = -1;
}
}
if (_text.Length == 0)
{
_text = "0";
}
if (_text == "-" || _text == "-0")
_value = 0;
else
{
_value = Convert.ToInt32(_text);
//Reformat value only if at end of field
if (_selstart == _text.Length)
{
_text = _value.ToString();
_selstart = _text.Length;
}
}
if (_selstart == 0)
//Reformat value only if no longer editing
_text = _value.ToString();
Text = _text;
SelectionStart = _selstart;
_fixingText = false;
}
[Category("Appearance")]
[DefaultValue(0)]
public int Value
{
get
{
FixText();
if (Text == "-")
return 0;
else
return Convert.ToInt32(Text);
}
set
{
Text = value.ToString();
}
}
[DefaultValue("0")]
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
FixText();
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
Keys k = (Keys)e.KeyChar;
if (e.KeyChar == '-')
return;
if (k == Keys.Delete || k == Keys.Back)
return;
if (Char.IsNumber(e.KeyChar))
return;
e.Handled = true;
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
SelectionStart = 0;
FixText();
}
}
}