C# | Winform程式設計控制元件之數字輸入框控制元件(numericUpDown)
阿新 • • 發佈:2018-11-11
數字輸入框控制元件是用於輸入數字和調節數字的一個控制元件,該控制元件中的數字儲存為decimal型別,但是數字必須是整數而不能是小數。
控制元件在工具箱中的樣式如下:
控制元件拖拽到視窗後的樣式如下:
常用屬性:
Value屬性:控制數字輸入框的數字的值(可用控制元件的向上或者向下符號對數字進行調節也可以自己輸入)。
Maxmum屬性:控制數字輸入框的最大值(當輸入的值大於最大值或者調節到大於最大值數字輸入框則顯示的是最大值,超過最大值也只顯示最大值)。
Minimum屬性:控制數字輸入框的最小值(可以為負數)。
Increment屬性:控制點選一次向上或者向下小按鈕數字輸入框值的增減大小。
UpDownAlign屬性:控制數字調節小按鈕是在控制元件的左邊還是右邊,有兩個值:Left和Right。
對應的屬性如下:
實現按住不放和按住拖拽增減數值的功能:
程式碼如下:(可自行提取裡面有用的部分)
需要用到的引數定義如下:
bool isMouseDown_PosX = false; //滑鼠是否按下
float posX_X = 0;
float posX_Y = 0;
float posX_lastValue = 0;
相關的事件響應函式如下:
//鍵盤按下時呼叫 private void numericUpDown_posX_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) //回車鍵 { ChangeWorldCoordinate(); } } //滑鼠按下時呼叫 private void numericUpDown_posX_MouseDown(object sender, MouseEventArgs e) { if (e.X > numericUpDown_posX.Size.Width - 15) { if (e.Button == MouseButtons.Right) //滑鼠右鍵 { ChangeWorldCoordinate(true); return; } if (e.Button == MouseButtons.Left) //滑鼠左鍵 { if (ModifierKeys == Keys.Shift) //按住Shift鍵時,點選滑鼠左鍵 { MessageBox.Show("Mouse And Key!"); } isMouseDown_PosX = true; posX_X = e.X; posX_Y = e.Y; ChangeWorldCoordinate(); } } } //滑鼠擡起時呼叫 private void numericUpDown_posX_MouseUp(object sender, MouseEventArgs e) { isMouseDown_PosX = false; } //滑鼠按下移動時呼叫 private void numericUpDown_posX_MouseMove(object sender, MouseEventArgs e) { if (isMouseDown_PosX) { float deltaX = e.X - posX_X; float deltaY = posX_Y - e.Y; float delta = 0; if (deltaX==0 && deltaY==0) { return; } //右、上方向 if (deltaX>0 || deltaY>0) { delta = (deltaX >= deltaY) ? deltaX : deltaY; if (delta > 0.5) { delta = 0.5f; } } //左、下方向 if (deltaX<0 || deltaY<0) { delta = (deltaX <= deltaY) ? deltaX : deltaY; if (delta < -0.5) { delta = -0.5f; } } numericUpDown_posX.Value += (decimal)delta; posX_X = e.X; posX_Y = e.Y; ChangeWorldCoordinate(); } } //數值發生改變時呼叫 private void numericUpDown_posX_ValueChanged(object sender, EventArgs e) { if (Math.Abs(numericUpDown_posX.Value - (decimal)posX_lastValue) != numericUpDown_posX.Increment) { return; } if (isMouseDown_PosX) { posX_lastValue = (float)numericUpDown_posX.Value; ChangeWorldCoordinate(); } }
實現按住拖拽功能思路如下:
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);