日期:2014-05-17  浏览次数:21117 次

Windows Form中的构造函数跟Form1.Load()有什么区别和联系
在创建一个窗体程序以后会出现
楼主有下面几个问题:
1.  private void Form1_Load(object sender, EventArgs e)是函数还是事件;
2.  为什么 我把写在 private void Form1_Load(object sender, EventArgs e)中的代码写在构造函数中也能  。  被运行,这两者有是什么区别?
3.  楼主知道构造函数是创建窗体对象是发生的,而Form1_Load是在构造函数之后,窗体显示之前运行的,那为       。  什么交换代码也可以运行?
4.  Form1_Load和构造函数到底具体的功能是什么?
5.. 在两者发生的中间那段时间中有什么事情发生吗?

------解决方案--------------------
没有构造函数中的
this.Load += Form_Load
Form1_Load还能执行么?
------解决方案--------------------
构造函数调用了
InitializeComponent()
VS为InitializeComponent()产生了如下代码:
...
this.Load += new System.EventHandler(this.Form1_Load);
...
这才有了Form1_Load

先把基本语法搞清楚吧。
------解决方案--------------------
程序环境初始化好所有的内容,然后设置Visible为true的时候,才会触发Load。因此你可以认为,这个事件说明基本上是万事俱备只欠东风了,你这这个事件进行自定义的操作不会遇到更多的诡异的异常初始化问题。

基本上,凡是需要在UI方面进行动态初始化的,都应该在这个事件去处理。以免初始化过早。
------解决方案--------------------
比如过你要在界面上动态显示“汽车仪表”控件,而这个仪表显然是在其它控件的最顶层的,甚至它需要与你在设计时拖到设计窗口里的某个控件交互,那么你把这个功能放在别的控件初始化完备之前显然就会出现问题了。

在Form_Load中做的事情,很明显就是要等到其它的控件都初始好之后才加载的。
------解决方案--------------------
实际上这个问题根本不用问,调试下,看下堆栈就知道了:
> WindowsFormsApplication1.exe!WindowsFormsApplication1.Form1.Form1_Load(object sender, System.EventArgs e) Line 22 C#
  System.Windows.Forms.dll!System.Windows.Forms.Form.OnLoad(System.EventArgs e) + 0x1a5 bytes OnLoad调用了Form.Load,这个函数可以被重写
  System.Windows.Forms.dll!System.Windows.Forms.Form.OnCreateControl() + 0x58 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.CreateControl(bool fIgnoreVisible) + 0x194 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.CreateControl() + 0x28 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.WmShowWindow(ref System.Windows.Forms.Message m) + 0x88 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m) + 0x2cb bytes
  System.Windows.Forms.dll!System.Windows.Forms.ScrollableControl.WndProc(ref System.Windows.Forms.Message m) + 0x2a bytes
  System.Windows.Forms.dll!System.Windows.Forms.ContainerControl.WndProc(ref System.Windows.Forms.Message m) + 0x10 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Form.WmShowWindow(ref System.Windows.Forms.Message m) + 0x3d bytes
  System.Windows.Forms.dll!System.Windows.Forms.Form.WndProc(ref System.Windows.Forms.Message m) + 0x209 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) + 0x11 bytes
  System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.