【问题标题】:equivalent code of winforms in WPFWPF中winforms的等效代码
【发布时间】:2013-06-14 09:28:15
【问题描述】:

我以前在 winfoms 工作过。有 KeyPress 事件。所以我可以得到 KeyChar。

下面的代码在winforms中工作

Dim allowedChars as String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "

If allowedChars.IndexOf(e.KeyChar) = -1
    If Not e.KeyChar = Chr(Keys.Back) Then
        e.Handled = True
        Beep()
    End If
End If

但是在WPF中我不知道如何实现上面的代码?

【问题讨论】:

  • 我认为那些不知道我的问题答案的人将其标记为否定。
  • @Vishal:我真的不这么认为。我认为人们会为他们在 SO 上找到的每一篇已经包含此问题的帖子都这样做(PS,我什至没有投反对票)。
  • 我没有投反对票,但如果您将鼠标悬停在投反对票按钮上,它会显示“问题不显示研究成果”。我认为他们的投票是有效的
  • @Vishal:这是为了验证文本框的输入吗?

标签: c# wpf vb.net winforms


【解决方案1】:

下面是C#,不过你可以很容易的把它转换成VB.NET。

private void NumericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    char c = (char)KeyInterop.VirtualKeyFromKey(e.Key);

    if ("ABCDEF".IndexOf(c) < 0)
    {
        e.Handled = true;
        MessageBox.Show("Invalid character.");
    }
}

您可能需要导入System.Windows.Input 以获取KeyInterop。上面的代码段进入TextBox的PreviewKeyDown事件。

以上所有内容及更多内容可见here

【讨论】:

  • 感谢您努力回答我的问题。但我想在我的文本框中添加一些特定的字母或符号,例如 A-Z、a-z、:?。我的意思是我希望文本框只接受 A-Z,a-z,:?.
  • 这很容易实现,不是吗?你已经有了传入的字符。您可以使用上面原始代码中的IndexOf 技术。让我更新我的代码。
  • @Vishal:更新了我的代码。您可以将 ABCDEF 替换为您希望在文本框中允许的所有字符。
  • 现在我想在列表中添加一些特殊键。像 backSpace、Home、End、PgUp、PgDown、箭头键、Insert 和我的应用程序的所有快捷键。这可能吗?
  • 当然。你可以通过if(e.Key != Key.Back &amp;&amp; e.Key != Key.Space) 等来实现。
【解决方案2】:

在 C# 中

private bool ValidChar(string _char)
{
   string Lista = @" ! "" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";
   return Lista.IndexOf(_char.ToUpper()) != -1;
}

private void textBoxDescripcion_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!ValidChar(e.Text))
         e.Handled = true;
}

在vb中

Private Function ValidChar(_char As String) As Boolean
    Dim Lista As String = " ! "" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z "
    Return Lista.IndexOf(_char.ToUpper()) <> -1
End Function

Private Sub textBoxDescripcion_PreviewTextInput(sender As Object, e As TextCompositionEventArgs)
    If Not ValidChar(e.Text) Then
        e.Handled = True
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多