數字輸入框控件是用於輸入數字和調節數字的一個控件,該控件中的數字儲存為decimal類型,但是數字必須是整數而不能是小數。
控件在工具箱中的樣式如下:

控件拖拽到窗口后的樣式如下:

常用屬性:
Value屬性:控制數字輸入框的數字的值(可用控件的向上或者向下符號對數字進行調節也可以自己輸入)。
Maxmum屬性:控制數字輸入框的最大值(當輸入的值大於最大值或者調節到大於最大值數字輸入框則顯示的是最大值,超過最大值也只顯示最大值)。
Minimum屬性:控制數字輸入框的最小值(可以為負數)。
Increment屬性:控制點擊一次向上或者向下小按鈕數字輸入框值的增減大小。
UpDownAlign屬性:控制數字調節小按鈕是在控件的左邊還是右邊,有兩個值:Left和Right。
對應的屬性如下:

實現按住不放和按住拖拽增減數值的功能:
代碼如下:(可自行提取里面有用的部分)
需要用到的參數定義如下:
1 bool isMouseDown_PosX = false; //鼠標是否按下
2 float posX_X = 0; 3 float posX_Y = 0; 4 float posX_lastValue = 0;
相關的事件響應函數如下:
1 //鍵盤按下時調用
2 private void numericUpDown_posX_KeyDown(object sender, KeyEventArgs e) 3 { 4 if (e.KeyCode == Keys.Enter) //回車鍵
5 { 6 ChangeWorldCoordinate(); 7 } 8 } 9
10 //鼠標按下時調用
11 private void numericUpDown_posX_MouseDown(object sender, MouseEventArgs e) 12 { 13 if (e.X > numericUpDown_posX.Size.Width - 15) 14 { 15 if (e.Button == MouseButtons.Right) //鼠標右鍵
16 { 17 ChangeWorldCoordinate(true); 18 return; 19 } 20
21 if (e.Button == MouseButtons.Left) //鼠標左鍵
22 { 23 if (ModifierKeys == Keys.Shift) //按住Shift鍵時,點擊鼠標左鍵
24 { 25 MessageBox.Show("Mouse And Key!"); 26 } 27 isMouseDown_PosX = true; 28 posX_X = e.X; 29 posX_Y = e.Y; 30 ChangeWorldCoordinate(); 31 } 32 } 33 } 34
35 //鼠標抬起時調用
36 private void numericUpDown_posX_MouseUp(object sender, MouseEventArgs e) 37 { 38 isMouseDown_PosX = false; 39 } 40
41 //鼠標按下移動時調用
42 private void numericUpDown_posX_MouseMove(object sender, MouseEventArgs e) 43 { 44 if (isMouseDown_PosX) 45 { 46 float deltaX = e.X - posX_X; 47 float deltaY = posX_Y - e.Y; 48 float delta = 0; 49 if (deltaX==0 && deltaY==0) 50 { 51 return; 52 } 53
54 //右、上方向
55 if (deltaX>0 || deltaY>0) 56 { 57 delta = (deltaX >= deltaY) ? deltaX : deltaY; 58 if (delta > 0.5) 59 { 60 delta = 0.5f; 61 } 62 } 63 //左、下方向
64 if (deltaX<0 || deltaY<0) 65 { 66 delta = (deltaX <= deltaY) ? deltaX : deltaY; 67 if (delta < -0.5) 68 { 69 delta = -0.5f; 70 } 71 } 72
73 numericUpDown_posX.Value += (decimal)delta; 74 posX_X = e.X; 75 posX_Y = e.Y; 76 ChangeWorldCoordinate(); 77 } 78 } 79
80 //數值發生改變時調用
81 private void numericUpDown_posX_ValueChanged(object sender, EventArgs e) 82 { 83 if (Math.Abs(numericUpDown_posX.Value - (decimal)posX_lastValue) != numericUpDown_posX.Increment) 84 { 85 return; 86 } 87 if (isMouseDown_PosX) 88 { 89 posX_lastValue = (float)numericUpDown_posX.Value; 90 ChangeWorldCoordinate(); 91 } 92 }
實現按住拖拽功能思路如下:
1:設置一個標記位,在鼠標按下時設為true;
2:在鼠標按下並移動時,判斷標記位的狀態,如果為true,則根據鼠標前后位置的增量,增減數值;
3:在鼠標抬起時,將標記位設置為false,不再進行移動時的事件響應;
這個控件沒有“ private void numericUpDown_posX_MouseMove(object sender, MouseEventArgs e)”這個時間,需要手動進行綁定,綁定方式如下:
this.numericUpDown_posX.MouseMove += new System.Windows.Forms.MouseEventHandler(this.numericUpDown_posX_MouseMove);
