限制TextBox输入,只能输入整数

 1     public class TextBoxInt : TextBox
 2     {
 3         public TextBoxInt()
 4         {
 5             KeyDown += TextBoxInt_KeyDown;
 6             TextChanged += TextBoxInt_TextChanged;
 7         }
 8 
 9         private void TextBoxInt_TextChanged(object sender, TextChangedEventArgs e)
10         {
11             //屏蔽非法字符粘贴
12             var textBox = sender as TextBox;
13             if (textBox != null)
14             {
15                 var change = new TextChange[e.Changes.Count];
16                 e.Changes.CopyTo(change, 0);
17 
18                 int offset = change[0].Offset;
19                 if (change[0].AddedLength > 0)
20                 {
21                     int num;
22                     if (!int.TryParse(textBox.Text, out num))
23                     {
24                         textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
25                         textBox.Select(offset, 0);
26                     }
27                 }
28             }
29         }
30 
31         private void TextBoxInt_KeyDown(object sender, KeyEventArgs e)
32         {
33             if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
34             {
35                 // 允许输入数字小键盘上的数字0-9
36                 e.Handled = false;
37             }
38             else if ((e.Key >= Key.D0 && e.Key <= Key.D9) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
39             {
40                 // 允许输入数字0-9,并且不能同时按着Shift键
41                 e.Handled = false;
42             }
43             else if (e.Key == Key.Enter)
44             {
45                 // 允许输入回车
46                 e.Handled = false;
47             }
48             else
49             {
50                 e.Handled = true;
51             }
52         }
53     }

 

转载于:https://www.cnblogs.com/candyzkn/p/3455641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值