c# - 从父级引发有关用户控件的事件

标签 c# events user-controls

我有一个具有以下重写事件的用户控件:

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Left )
        DoSomething();
}

当我将用户控件放在主窗体上时,不会触发此事件。
如何从父表单访问此事件?

protected override void OnKeyDown(KeyEventArgs e)
{
    e.Handled = true;
    if (e.KeyCode == Keys.Left)
        Move(pt.X,pt.Y);//Move is a function within the usercontrol
    else if (e.KeyCode == Keys.Right)
        Move(pt.X,pt.Y);
   //other conditions
   e.Handled = false;
}

我需要通知家长这个事件

最佳答案

如果我没理解错的话,您正试图从父窗体中调用用户控件的 OnKeyDown 方法。
这是主窗体类:

public class Form1 : Form
{
    private UserControl1 myControl;

    public Form1()
    {
        myControl = new UserControl1();
        Controls.Add(myControl);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        myControl.InvokeOnKeyDown(e);
    }
}

这是用户控件:

public class UserControl1 : UserControl
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        MessageBox.Show("Key Down Fired!");
    }

    public void InvokeOnKeyDown(KeyEventArgs e)
    {
        OnKeyDown(e);
    }
}

关于箭头键的编辑:箭头键通常不被视为输入键,因此不会传递给按键方法。要更改此设置,您必须重写 IsInputKey 方法:

 protected override bool IsInputKey(Keys e)
 {
     if (e == Keys.Up || e == Keys.Down ||
         e == Keys.Left || e == Keys.Right) return true;
     return base.IsInputKey(e);
 }

关于c# - 从父级引发有关用户控件的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8692680/

相关文章:

c# - Angular 6 - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header

c# - ListBox ItemTemplate 中的 Togglebutton 中的 Textblock 中的文本换行

apache-flex - 弹性 : Determine if a component is showing

asp.net - 从动态注册用户控件中获取值

c# - 如何强制以父类(super class)形式放置控件?

jquery - 在占位符中动态创建的用户控件中的 Css 和 js 文件引用

c# - 如果我正在读取的字节不存在,BinaryReader 会做什么?

c# - WPF DataGridRow ContextMenu MenuItem 单击事件未触发

jQuery : how to custom a CLICK event?

c# - C# 事件创建的 VB 等效项