TextBox只允许输入数字,最大长度为10
//TextBox.ShortcutsEnabled为false 禁止右键和Ctrl+v private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) { //只允许输入数字,粘贴数字 if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8)) { e.Handled = true; } } //允许Ctrl+v粘贴数字 private void txtNumber_KeyUp(object sender, KeyEventArgs e) { if (e.KeyData == (Keys.Control | Keys.V)) { if (Clipboard.ContainsText()) { try { Convert.ToInt64(Clipboard.GetText()); //检查是否数字 ((TextBox)sender).SelectedText = Clipboard.GetText().Trim(); //Ctrl+V 粘贴 if (((TextBox)sender).TextLength > 10) { ((TextBox)sender).Text = ((TextBox)sender).Text.Remove(10); //TextBox最大长度为10 移除多余的 } } catch (Exception) { e.Handled = true; //throw; } } } }
第二种办法:
1、先创建一个ToolStripMenuItem,添加 菜单列表 “复制” 和 “粘贴” 。
2、设置同一事件txtToolStripMenuItem_Click
//复制粘贴处理 private void txtToolStripMenuItem_Click(object sender, EventArgs e) { string txtname = ((ToolStripMenuItem)sender).Text; if (txtname.Equals("复制")) { SendKeys.SendWait("^c"); //Ctrl + C } if (txtname.Equals("粘贴")) { SendKeys.SendWait("^v"); //Ctrl + V } }
3、TextBox 属性 ContextMenuStrip 绑定 ToolStripMenuItem
4、TextBox添加事件txtOrderID_KeyPress
//只允许输入数字,粘贴数字 private void txtOrderID_KeyPress(object sender, KeyPressEventArgs e) { //只允许输入数字,粘贴数字 if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8 || e.KeyChar == (char)3 || e.KeyChar == (char)22)) { e.Handled = true; } try { if (e.KeyChar == (char)22) { Convert.ToInt64(Clipboard.GetText()); //检查是否数字 Clipboard.SetText(Clipboard.GetText().Trim()); //去空格 } } catch (Exception) { e.Handled = true; //throw; }
5、ToolStripMenuItem 菜单 “复制” 和 “粘贴” 创建 同一Click事件。
//复制粘贴处理 private void txtToolStripMenuItem_Click(object sender, EventArgs e) { string txtname = ((ToolStripMenuItem)sender).Text; if (txtname.Equals("复制")) { SendKeys.SendWait("^c"); //Ctrl + C } if (txtname.Equals("粘贴")) { SendKeys.SendWait("^v"); //Ctrl + V } }