C# 强制转换文本框KeyEventArgs

C# 强制转换文本框KeyEventArgs,c#,winforms,events,casting,keyevent,C#,Winforms,Events,Casting,Keyevent,我试图在运行时获取textBox控件的KeyUp事件,但我很难正确地强制转换。下面的代码已编译,我可以在添加Watch/Inspect RTBPrivatontote_KeyUp->EventArgs e时看到事件信息: public class Form1 { private System.Windows.Controls.TextBox rtbPrivateNote = null; public InitFormControls() { Lo

我试图在运行时获取textBox控件的KeyUp事件,但我很难正确地强制转换。下面的代码已编译,我可以在添加Watch/Inspect RTBPrivatontote_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
       }
    }
}

您正在混合使用WinForms和WPF控件/代码。您订阅的事件不是WinForms的默认事件,而是WinForms的默认事件。您为什么要通过
ref
传递
panelRichText
?@flydog我正在使用面板在运行时保存文本控件。@IvanStoev没有使用WPF控件-我想您看到了控件名“WPFControlName”我从以前使用的一些代码复制了它-我现在重命名了它,但它只是指定的控件名。我看到您正在函数中使用
panelRichText
控件,但您没有更改参数的值。您不需要通过ref传递它。您可以通过说
if(e是KeyEventArgs ke)
来简化此操作,并且去掉前一行(进行转换),这没有任何意义。请再次阅读我在问题下的评论。您试图将角色转换为错误的类型。确保如果
private void rtbprivatontote\u KeyUp(对象发送方,KeyEventArgs e)
不会编译,则将永远不会输入上述
if
。您只需在事件处理程序签名中使用正确的KeyEventArgs类型。