[英]c# How do I catch Windows Form Events in user control?
I have made a user control for search. 我已经做了搜索的用户控件。 In the time of searching a popup will open.
在搜索时会弹出一个窗口。 Now I want to access Form_Resize and Form_LocationChanged event from the user control.
现在,我想从用户控件访问Form_Resize和Form_LocationChanged事件。
In Control constructor, you have to subscribe to ParentChanged
event of the control to know when you can get your controls current parent. 在控件构造函数中,您必须预订控件的
ParentChanged
事件,才能知道何时可以获取控件的当前父级。
public YourControl()
{
InitializeComponent();
ParentChanged += OnParentchanged;
}
private void OnParentchanged(object sender, EventArgs e)
{
// maybe get Form istead of just parent control
Parent.Resize += OnParentResize;
Parent.LocationChanged += OnParentLocationChanged;
}
Then you have to subscribe to the form's events that you need. 然后,您必须订阅所需的表单事件。 The thing is, that
Parent
of your control might be another control, so you may want to recursively search all Parents
until it's form. 事实是,您的控件的
Parent
可能是另一个控件,因此您可能要递归搜索所有Parents
直到它形成为止。 It is just not that really that clear what do you want to achieve. 并不是很清楚您想要实现什么。
Also, remember that you have unsubscribe from events of a previous parent if it changes. 另外,请记住,如果前一个父级发生更改,您将取消订阅该事件。 But that's another and a very tricky question.
但这是另一个非常棘手的问题。
EDIT: 编辑:
You don't need to recursively search for the form by yourself, there is a FindForm()
method, that was mentioned by @jmcilhinney 您不需要自己递归搜索表单,@ jmcilhinney提到了一个
FindForm()
方法。
Every control has a FindForm
method that will return the form that contains the control, even if there are other controls in between in the hierarchy. 每个控件都有一个
FindForm
方法,该方法将返回包含该控件的表单,即使层次结构之间也存在其他控件。 Once you have a reference to the form, you can handle its events in exactly the same way as you would any other object's at run time. 一旦引用了表单,就可以使用与其他对象在运行时完全相同的方式来处理其事件。
The Parent object might be null if you try to access it from the constructor. 如果尝试从构造函数访问它,则Parent对象可能为null。 What I had to do was add the reference in the Load event for the UserControl.
我要做的是在UserControl的Load事件中添加引用。
private void CustomControl_Load(object sender, EventArgs e)
{
ParentChanged += OnParentChanged;
}
private void OnParentChanged(object sender, EventArgs e)
{
Parent.Resize += OnParentResize;
Parent.LocationChanged += OnParentLocationChanged;
// More events or
// Do Something...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.