从尚不存在的表单创建事件. [英] Create an event from a form that doesn't yet exist.
问题描述
如果尚未创建表单,该如何创建form_load事件?
如果我使用:
How would I create a form_load event if the form hasn''t been created yet?
If I use:
Form x = new Form();
x.Visible = true;
我将如何从中创建一个事件?这样,在加载时就会显示MessageBox.
感谢您的帮助.
How would I create an event from this? So that when it loads a MessageBox would show up.
Thanks for any help.
推荐答案
在现实生活中,您永远不会调用问题中显示的代码,因为您从未创建System.Windows.Forms.Form
的实例.相反,您总是使用Form
作为基类来创建派生类.您为表单类创建一个构造函数.在这里您可以设置所有事件句柄,并且在大多数情况下应该如此.它会完全按照您的意愿进行:在创建表单实例之前.
In real life, you never call the code you have shown in the Question, because you never create an instance ofSystem.Windows.Forms.Form
. Instead, you always create a derived class usingForm
as a base class. You create a constructor for your form class. This is where you can setup all event handles, and in most cases should. It will happen exactly as you wanted: before the instance of the form is created.
public class MyForm : Form {
public MyForm {
this.Load += (sender, eventArgs) =&ft; {
MessageBox.Show(
"If you can read this, the form is not yet created. Hope you will see it later",
string.Format(" {0}: before showing the form", Application.ProductName));
};
//...
}
}
您可以以这种方式处理任何其他表单事件,并以这种方式为所有表单控件设置事件.事件Form.Load
是一种虚构"事件,在所有其他表单事件之前直接调用.即使经常处理此事件,也绝对不是必须的.相反,您可以从Form构造函数简单地调用其处理程序.通常,您应该设置事件Form.Shown
,Form.FormClosing
,FormFormClosed
.在这些情况下,处理事件至关重要.
You can handle any other form event this way and setup events for all of the form''s controls in this way. The event Form.Load
is kind of "fictional" event, simply invoked before all other form event directly. Even though this event is often handled, it is never absolutely required. Instead, you can simplu call its handler from the Form constructor. More typically, you should setup the event Form.Shown
, Form.FormClosing
, FormFormClosed
. In these cases handling events is essentially important.
有几种方法可以完成您想要的事情.
第一个也是最简单的方法是使用设计器为"x"设计表单,并以常规方式创建FormLoad
处理程序.
如果必须从创建x的Form
中控制它,则类似以下内容:
There are several ways to do what you want.
The first, and easiest, to design the Form for ''x'' using the designer and just create aFormLoad
handler in the normal way.
If you must control this from theForm
that creates x then something like:
Form x = new Form();
x.Load += this.OnXLoad;
x.Show() // Note Show() NOT visible. You could also use ShowDialog() which would make x Modal
..............................
..............................
..............................
..............................
..............................
private void OnXLoad(object sender, System.EventArgs e)
{
MessageBox.Show("Boo");
}
如果我理解正确,可以使用
if i understand it correctly, you can use
this.VisibleChanged += new System.EventHandler(Form1_VisibuleChanged);
每当您更改可见性时,都会有一个消息框显示"hello"
have a message box show ''hello'', whenever you change the Visibility
这篇关于从尚不存在的表单创建事件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!