【问题标题】:I can not find KeyPress event handler in c#我在 C# 中找不到 KeyPress 事件处理程序
【发布时间】:2016-03-25 23:54:18
【问题描述】:

我是 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,我仍会收到错误“密钥在当前上下文中不存在”。我完全不知所措,如果有人可以提供帮助,那就太好了。

【问题讨论】:

  • 必须是Keys.D0Keys.D9
  • 当您说 Windows 10 应用程序时,您的意思是您要编写一个所谓的“通用应用程序”吗?

标签: c# textbox win-universal-app keypress


【解决方案1】:

假设“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;
    }
}

【讨论】:

  • 再问一个问题,我怎样才能让它在文本框中没有超过一个小数点?
  • 当key为小数点时,检查TextBox中是否已经包含一个,并相应设置Handled。
【解决方案2】:

假设这是一个 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;
    }
}

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    您可以使用自定义代码手动生成此事件。我希望你能明白。

        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.
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 2016-05-28
      相关资源
      最近更新 更多