![](/img/trans.png)
[英]How I can bound a checkBox with KeyPress event of a textBox in C#
[英]I can not find KeyPress event handler in c#
我是 C# 的新手。 我正在嘗試制作一個 Windows 10 應用程序,其中我有一個只接受數字和一位小數的文本框。 我在這里看到很多人說要使用 KeyPress 事件處理程序,但我沒有。 我只有 KeyDown 和 KeyUp。 我看到有人在 KeyDown 中使用以下代碼發帖:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key < Key.D0 || e.Key > Key.D9)
{
e.Handled = true;
}
}
但即便如此,我還是收到了 Key.D0 和 Key.D9 的錯誤“當前上下文中不存在密鑰”。 我完全不知所措,如果有人可以提供幫助,那就太好了。
假設“Windows 10 應用程序”是指“通用應用程序”,則可以在名為TextBox_KeyDown
的方法中使用以下代碼,該方法與 TextBox 的KeyDown
事件相關聯。
private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if(e.Key < Windows.System.VirtualKey.Number0 || e.Key >= Windows.System.VirtualKey.Number9)
{
e.Handled = true;
}
}
假設這是一個 WinForm 應用程序,請參閱 MSDN 上的以下Control.KeyPress Event
示例(重新: https ://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress( v=vs .110).aspx )
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the condition
if (SOME CONDITION)
{
// Stop the character from being entered into the control.
e.Handled = true;
}
}
希望這可能會有所幫助。
您可以使用自定義代碼手動生成此事件。 我希望你能明白。
public YourFormName()
{
InitializeComponent();
this.KeyPress -= YourFormName_KeyPress;
this.KeyPress += YourFormName_KeyPress;
}
private void YourFormName_KeyPress(object sender, KeyPressEventArgs e)
{
//Check for any key you want.
if (e.KeyChar == (char)Keys.Enter)
{
//do anything.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.