投射文本框 KeyEventArgs

Casting Textbox KeyEventArgs

我正在尝试在运行时获取文本框控件的 KeyUp 事件,但我很难正确投射。下面的代码编译,当我添加 Watch/Inspect rtbPrivateNote_KeyUp -> EventArgs e:

时,我可以看到事件信息
public class Form1
{
    private System.Windows.Controls.TextBox rtbPrivateNote = null;
    
    public InitFormControls()
    {
        LoadSpellChecker(ref pnlPrivateNotes, ref rtbPrivateNote, "txtPrivateNotePanel");
        rtbPrivateNote.TextChanged += new System.Windows.Controls.TextChangedEventHandler(rtbPrivateNote_TextChanged);
        rtbPrivateNote.KeyUp += new System.Windows.Input.KeyEventHandler(rtbPrivateNote_KeyUp);
    }
    
    private void LoadSpellChecker(ref Panel panelRichText, ref System.Windows.Controls.TextBox txtWithSpell, string ControlName)
    {
        txtWithSpell = new System.Windows.Controls.TextBox
        {
            Name = ControlName
        };
        txtWithSpell.SpellCheck.IsEnabled = true;
        txtWithSpell.Width = panelRichText.Width;
        txtWithSpell.Height = panelRichText.Height;
        txtWithSpell.AcceptsReturn = true;
        txtWithSpell.AcceptsTab = true;
        txtWithSpell.AllowDrop = true;
        txtWithSpell.IsReadOnly = false;
        txtWithSpell.TextWrapping = System.Windows.TextWrapping.Wrap;
    
        ElementHost elementHost = new ElementHost
        {
            Dock = DockStyle.Fill,
            Child = txtWithSpell
        };
    
        panelRichText.Controls.Add(elementHost);
    }
    
    // private void rtbPrivateNote_KeyUp(object sender, KeyEventArgs e)  // WONT COMPILE
    private void rtbPrivateNote_KeyUp(object sender, EventArgs e)
    {
        //if (e.Key == Key.Enter  
        //    || e.Key == Key.Return)
        //{
        //    Do Something here
        //}
    }
}

你不能那样转换它,因为 KeyEventArgs 派生自 EventArgs,并且由于 e 不是 KeyEventArgs,它说它不能转换它。

如果 e 是 KeyEventArgs 类型,那么您可以将其转换为 EventArgs。

private void rtbPrivateNote_KeyUp(object sender, EventArgs e)
{
    KeyEventArgs ke = e as KeyEventArgs;
    if (ke != null)
    {
       if (ke.Key == Key.Enter  || ke.Key == Key.Return)
       {
        //Do Something here
       }
    }
}