【问题标题】:numeric TextBox keydown数字文本框按键
【发布时间】:2011-12-30 10:09:25
【问题描述】:

我想制作一个文本框数字。想法是在文本显示在文本框中之前检查按下的键。我实现了 TextBox 的方法 KeyDown()。 这是我的代码:

private void txtX_KeyDown(object sender, KeyEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
    {
        e.Handled = true;
    }
}

KeyEventArgs 没有 KeyChar(我是从教程中得到的)

我使用 WPF

【问题讨论】:

  • 我认为你的做法是错误的,看看这个问题:stackoverflow.com/questions/1268552/…
  • 无论如何,您的实际问题是什么? KeyEventArgs 有一个 Key 属性来查看按下了什么。
  • 不要重新发明轮子。互联网上有大量数字文本框的示例。
  • KeyPress 事件具有包含 KeyChar 属性的 KeyPressEventArgs 参数。 Resume - 使用 KeyPress 事件代替 KeyDown
  • @Reniuz 他正在使用WPF TextBox。没有 KeyPress 事件。

标签: c# wpf textbox numeric keydown


【解决方案1】:

对于windows窗体

e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57); 对于 wpf e.Handled = !("D1D2D3D4D5D6D7D8D9D0".Contains(e.Key.ToString())); 我正在使用 VS2010 使用相同的逻辑 U 可以做一个更好的解决方案,更优雅:)

【讨论】:

  • 没有 SuppressKeyPress。 WPF 不是 WinForms。
  • ups,我没有看到标签 wpf :(
  • 使用相同想法的 wpf 的其他解决方案是 e.Handled = !("D1D2D3D4D5D6D7D8D9D0".Contains(e.Key.ToString()));
  • 您的解决方案的问题是,文本框中允许使用字符“d”。
  • e.Handled = (e.Key < Key.D0 || e.Key > Key.D9) && (e.Key < Key.NumPad0 || e.Key > Key.NumPad9);
【解决方案2】:

我认为 KeyEventArgs 没有 KeyChar 属性。您可以查看

KeyEventArgs定义如下。

public class KeyEventArgs : EventArgs
{
    // Fields
    private bool handled;
    private readonly Keys keyData;
    private bool suppressKeyPress;

    // Methods
    public KeyEventArgs(Keys keyData);

    // Properties
    public virtual bool Alt { get; }
    public bool Control { get; }
    public bool Handled { get; set; }
    public Keys KeyCode { get; }
    public Keys KeyData { get; }
    public int KeyValue { get; }
    public Keys Modifiers { get; }
    public virtual bool Shift { get; }
    public bool SuppressKeyPress { get; set; }
}

您可以尝试将键值转换为字符,请参考以下示例。

private string keyChar = string.Empty;

// Convert KeyValue to char
private void SomeKeyDown(object sender, KeyPressEventArgs e)
{
    keyChar = (char)e.KeyValue;
}

【讨论】:

    【解决方案3】:

    如果您使用的是 WinForms,过滤字符最简单的方法是在 KeyPress 事件中。

    private void txtX_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
    }
    

    【讨论】:

      【解决方案4】:

      然后你这样做:

              if (e.Key == Key.D)
                  e.Handled = true;
              else
                  e.Handled = !("D1D2D3D4D5D6D7D8D9D0".Contains(e.Key.ToString()));
      

      :D

      【讨论】:

        【解决方案5】:

        使用此代码。

        private void txtbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !("D1D2D3D4D5D6D7D8D9D0".Contains(e.Key.ToString()));  
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-12
          • 2010-12-15
          • 2010-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多