How Can I make the event of Activate Windows to run only one time?
In order to make the event of Activate Windows to run only one time, I write the code below
this.Activated-=new System.EventHandler(this.Form1_Activated);
Is it correct? but It certain can work well. but it seems it is not a good code.
| |
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WindowsApplication1 { publicclass Form1 : System.Windows.Forms.Form { private System.ComponentModel.Container components =null; public Form1() { InitializeComponent(); } protectedoverridevoid Dispose(bool disposing ) { if( disposing ) { if (components !=null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows privatevoid InitializeComponent() { this.AutoScaleBaseSize =new System.Drawing.Size(6, 14); this.ClientSize =new System.Drawing.Size(292, 266); this.Name = "Form1"; this.Text = "Form1"; this.Activated +=new System.EventHandler(this.Form1_Activated); } #endregion [STAThread] staticvoid Main() { Application.Run(new Form1()); }
privatevoid Form1_Activated(object sender, System.EventArgs e) { this.Activated-=new System.EventHandler(this.Form1_Activated); } } }
|
[2846 byte] By [
CUIWEI] at [2007-12-16]
The code is certainly correct.
I find it better to override the method that actually raises the event, instead of attaching to it. However this is typically a personal preference.
For example:
| | public class Form1 : Form { ... private bool _FirstActivate = true; protected override OnActivated(EventArgs e) { if (_FirstActivate) { _FirstActivate = false; ... } base.OnActivated(e); } } |
Have you tested it? My initial reaction was that this can't work.
| | this.Activated-=new System.EventHandler(this.Form1_Activated); |
here you are removing a NEW event handler for the method, not the one allready added.
| |
private void Form1_Activated(object sender, EventArgs e) { this.Activated -= activEventHandler; } //these two items is to be put in the designer in whidbey private System.EventHandler activEventHandler; this .Activated += (activEventHandler = new System.EventHandler(this.Form1_Activated));
|