我有一个具有以下重写事件的用户控件:
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/