来源:中国自学编程网收集整理
1、重写键盘事件OnKeyPress() protected override void { base.OnKeyPress(e); if (this.ReadOnly) // 只读, 不处理 return; if ((int)e.KeyChar <= 32) // return; if (!char.IsDigit(e.KeyChar)) // { e.Handled = true; return; } }
{ if (keyData == (Keys)Shortcut.CtrlV) // 快捷键 Ctrl+V 粘贴操作 { this.ClearSelection(); string text = Clipboard.GetText(); for (int k = 0; k < text.Length; k++) // can not { // 通过消息模拟键盘输入, SendKeys.Send()静态方法不行 SendCharKey(text[k]); } return true; } return base.ProcessCmdKey(ref msg, keyData); }
private void SendCharKey(char c) // 通过消息模拟键盘录入 { Message msg = new Message(); msg.HWnd = this.Handle; msg.Msg = WM_CHAR; // 输入键盘字符消息 msg.WParam = (IntPtr)c; msg.LParam = IntPtr.Zero; base.WndProc(ref msg); }
{ // 创建无内容菜单对象, 等价屏蔽该控件的上下文菜单 this.ContextMenu = new ConTextMenu(); } 由于上下文菜单的Paste操作对应Windows的WM_PASTE消息,于是可以在控件的WndProc()方法中捕获该消息,然后获得剪切板 { if (m.Msg == WM_PASTE) // 选择上下文菜单的"粘贴"操作 { this.ClearSelection(); SendKeys.Send(Clipboard.GetText()); // 模拟键盘输入 } else { base.WndProc(ref m); } }
{ if (this.SelectionLength == 0) return; int selLength = this.SelectedText.Length; this.SelectionStart += this.SelectedText.Length; // 光标在选择之后 this.SelectionLength = 0; for (int k = 1; k <= selLength; k++) this.DeleteText(Keys.Back); }
private void DeleteText(Keys key) // 删除字符并计算SelectionStart值 { int selStart = this.SelectionStart; if (key == Keys.Delete) // 转换Delete操作为BackSpace操作 { selStart += 1; if (selStart > base.Text.Length) return; } if (selStart == 0 || selStart > base.Text.Length) // return; if (selStart == 1 && base.Text.Length == 1) { base.Text = ""; base.SelectionStart = 0; } else // selStart > 0 { base.Text = base.Text.Substring(0, selStart - 1) + base.SelectionStart = selStart - 1; } }
|