zoukankan      html  css  js  c++  java
  • 限制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     }
  • 相关阅读:
    bzoj2957 -- 线段树
    bzoj2209 [ JSOI2011 ] -- splay
    bzoj3874 [ AHOI2014 ] -- 爬山算法
    bzoj1038 [ ZJOI2008 ] -- 模拟退火+二分
    bzoj2428 [ HAOI2006 ] -- 模拟退火
    bzoj3680 -- 模拟退火
    bzoj4500 -- 差分约束
    bzoj3527 -- FFT
    bzoj1013 [ JSOI2008 ] -- 高斯消元
    使用nginx try_files 指令 管理静态资源
  • 原文地址:https://www.cnblogs.com/candyzkn/p/3455641.html
Copyright © 2011-2022 走看看