我有一个具有以下重写事件的用户控件:
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;
}
我需要父母在此事件上收到通知
答案 0 :(得分:1)
根据您发布的更新问题和代码示例,如果您希望通知父表单发生移动操作,则需要在UserControl中创建一个事件并以父表单订阅它。这可以通过以下示例实现。如果这可以解决您的问题,请告诉我,否则请发布更多详细信息。
祝你好运
// Define custom EventArgs to pass into the Move event
public class MoveEventArgs : EventArgs
{
private Point _movePoint;
public MoveEventArgs(Point movePoint)
{
_movePoint = _movePoint;
}
public Point MovePoint { get { return _movePoint; } }
}
// Define a custom user control that raises an event to subscribers on move
public class MyUserControl : UserControl
{
public event EventHandler<MoveEventArgs> Moved;
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
OnMoved(pt);
}
else if (e.KeyCode == Keys.Right)
{
Move(pt.X,pt.Y);
OnMoved(pt);
}
//other conditions
e.Handled = false;
}
// Raises a custom event, Moved
protected void OnMoved(Point movePoint)
{
var handler = Moved;
if (handler != null)
{
handler(this, new MoveEventArgs(movePoint);
}
}
}
// How to subscribe to the event (and be notified of move)
public class MyParentForm : Form
{
public MyParentForm()
{
InitializeComponent();
_myUserControl.Moved += new EventHandler<MoveEventArgs>(MyUserControl_Moved);
}
private void MyUserControl_Moved(object sender, MoveEventArgs e)
{
// e.MovePoint now contains the point that the usercontrol was moved to
// this event will fire whenever the user presses Left or Right arrow
}
}
答案 1 :(得分:1)
如果我理解正确,您试图从父表单中调用用户控件的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);
}