在按键事件中,我使用代码here禁用某些键(例如,我想只允许键入数字)。但是,这也会禁用CTRL-C等快捷方式。我仍然可以用鼠标复制和粘贴,我仍然可以使用那些我不使用KeyPressEventHandler
的剪贴画。
以下是我正在使用的代码:
class IntegerTextBox : TextBox
{
public IntegerTextBox()
{
KeyPress += new KeyPressEventHandler(accept_only_digits); //disable "wrong" key presses, https://stackoverflow.com/a/4285768/2436175
}
void accept_only_digits(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsNumber(ch) && ch != (char)Keys.Back && ch != (char)Keys.ControlKey) //The latter doesn't help
{
e.Handled = true;
return;
}
}
}
然而,KeyPressEventArgs与KeyEventArgs不同,似乎没有必要知道是否按下了ctrl键。有没有办法规避这个?例如,如果当前按下了ctrl键,则阻止调用KeyPressEventHandler
的东西?
答案 0 :(得分:1)
变化:
ch != (char)Keys.ControlKey.
成:
!char.IsControl(ch)
This also makes superfluous your check for backspace
顺便说一句,我在我的"只有int textbox"中使用差异方法。覆盖从here引导的覆盖文本。
void TextBoxOnlyInt_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '-'))
{
e.Handled = true;
}
if (e.KeyChar == '-')
if ((sender as TextBox).Text.Length != (sender as TextBox).SelectionLength)
if ((sender as TextBox).Text.Length > 0)
e.Handled = true;
}
protected override void WndProc(ref Message m)
{
int i;
if (m.Msg == 0x302)
if (int.TryParse(Clipboard.GetText(), out i))
{
//some restrict to avoid pasted make textbox value become invalid
if (i < 0 && this.SelectionStart != 0)
return;
else if (i < 0 && this.Text[0] == '-')
return;
else if (this.SelectionStart == 0 && this.Text[0] == '-')
return;
else
{
this.SelectedText = Clipboard.GetText();
return;
}
}
else return;
base.WndProc(ref m);
}
答案 1 :(得分:0)
修改:请参阅Nam Binh's solution,这更加简单明了。
我通过添加KeyDown / KeyUp事件处理程序并保存控制键的当前状态来解决。它似乎有用......
class IntegerTextBox : TextBox
{
private bool controlDown;
public IntegerTextBox()
{
controlDown = false;
KeyPress += new KeyPressEventHandler(accept_only_digits); //disable "wrong" key presses, https://stackoverflow.com/a/4285768/2436175
KeyDown += new KeyEventHandler(update_control_status);
KeyUp += new KeyEventHandler(update_control_status);
}
void update_control_status(object sender, KeyEventArgs e)
{
controlDown = e.Control;
}
void accept_only_digits(object sender, KeyPressEventArgs e)
{
if (controlDown)
{
return;
}
char ch = e.KeyChar;
//[...]