views:

396

answers:

2

Hi, is there a way I can get a Load event for System.Windows.Forms.Control just like System.Windows.Forms.Form.Load?

I want to run some initialize code before the control first shown.

Also, it would be nice to be able to do the same for System.Windows.Forms.ToolStripStatusLabel which is not actually a Control, but works like one.

Ideally, I can do this: control.OnLoad(() => { dosomething here; });

in which OnLoad is a extension method that would run the argument Action when the "control" "Loads".

Thanks!

+1  A: 

Form's Load event is called by the OnLoad method which is called from the OnCreateControl method which belongs to the Control class. So for the form the calling sequence would be following:

OnCreateControl start
  OnLoad start
      Form Load event call
  OnLoad finish
OnCreateControl finish

I guess you can override OnCreateControl for your component and add your optimization code there.

hope this helps, regards

serge_gubenko
Thanks for your tip. Followed your advice I found CreateControl event of Control class. Is there something like this in ToolStripItem class?
deerchao
Are you trying to create new ToolStripItem descendant? I guess you can put the initialization code into its contructor
serge_gubenko
No I can't because the code has something to do with its parent: the ToolStrip control. in the constructor, they'd be null.
deerchao
you can use OnOwnerChanged(EventArgs e) method to track the Owner property change; and OnParentChanged(ToolStrip oldParent, ToolStrip newParent) to handle parent control change. Both should be called when ToolStripItem get added to the StatusStrip control items collection
serge_gubenko
+1  A: 

For a control you can override either OnControlCreated or OnHandleCreated. The latter one can fire multiple times if it is necessary to recreate the control window. Be sure to use it if your code affects the window itself. In other words, if you do anything that requires the Handle property.

Few suitable choices for a ToolStripItem derived control. I'd recommend overriding SetVisibleCore() or OnAvailableChanged() or the AvailableChanged event. They run when the Visible property of the ToolStripItem changes. Beware that it may fire multiple times, keep a bool field that tracks that your initialization code has already run.

Last but not least, be sure to only do any of this if your code actually requires the control to be created. The vast majority of init code can go in the constructor. You only need a Load event if your code depends on the actual Location and Size of the control. Which might be different from the designer value if the form rescales itself due to a different system font or video DPI setting on the target machine.

Hans Passant
Thanks. I tested it, but not working like I expected. The VisibleChanged/AvailableChanged event fires when their GetCurrentParent() is null.
deerchao