-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNumericTextBox.cs
84 lines (77 loc) · 2.81 KB
/
NumericTextBox.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
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsControls
{
public class NumericTextBox : TextBox
{
private int WM_KEYDOWN = 0x0100;
int WM_PASTE = 0x0302;
public override bool PreProcessMessage(ref Message msg)
{
if (msg.Msg == WM_KEYDOWN)
{
var keys = (Keys)msg.WParam.ToInt32();
bool numbers = ((keys >= Keys.D0 && keys <= Keys.D9) ||
(keys >= Keys.NumPad0 && keys <= Keys.NumPad9)) &&
ModifierKeys != Keys.Shift;
bool ctrl = keys == Keys.Control;
bool ctrlZ = keys == Keys.Z && ModifierKeys == Keys.Control,
ctrlX = keys == Keys.X && ModifierKeys == Keys.Control,
ctrlC = keys == Keys.C && ModifierKeys == Keys.Control,
ctrlV = keys == Keys.V && ModifierKeys == Keys.Control,
del = keys == Keys.Delete,
bksp = keys == Keys.Back,
arrows = (keys == Keys.Up)
| (keys == Keys.Down)
| (keys == Keys.Left)
| (keys == Keys.Right);
if (numbers | ctrl | del | bksp | arrows | ctrlC | ctrlX | ctrlZ)
{
return false;
}
else if (ctrlV)
{
// handle pasting from clipboard
var clipboardData = Clipboard.GetDataObject();
var input = (string)clipboardData.GetData(typeof(string));
foreach (var character in input)
{
if (!char.IsDigit(character)) return true;
}
return false;
}
else
{
return true;
}
}
else
{
return base.PreProcessMessage(ref msg);
}
}
/// <summary>
/// Get int value from Text property or 0 if not an int
/// </summary>
[Browsable(false)]
public int AsInteger => int.TryParse(Text, out var value) ? value : 0;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)
{
var clipboardData = Clipboard.GetDataObject();
var input = (string)clipboardData.GetData(typeof(string));
foreach (var character in input)
{
if (!char.IsDigit(character))
{
m.Result = (IntPtr)0;
return;
}
}
}
base.WndProc(ref m);
}
}
}