开发者

Triggering an event after a Winform layout is complete

I am working on a C# WinForm application.

I want to trigger some processing once the form has been "shown" and the layout of the form is complete.

I am using the "_Shown" event, but this seems to trigger before the layout of the form has completed. Is there event I can use that fires 开发者_Python百科once the layout is complete?


Put Application.DoEvents() at the start of the form's Shown event handler. This will force all the controls to be rendered.


I don't see an event after Shown you can use for this purpose. Could you not use a timer to delay your processing in the Shown event?


An old trick in VB6 used to be to use the Paint event:

bool firstShown = false;

void form_Paint(Object sender, EventArgs e) {
  if ( !firstShown ) {
    YourMethodThatNeedsToRunOnShown();
    firstShown = true;
  }

  //the rest of your paint method (if any)

}

It is a little hacky, but it does work


This works for me and is much less "hacky" than other suggestions:

protected override void OnLayout(LayoutEventArgs levent)
{
    base.OnLayout(levent);

     if(someControl == null)
       return; // be careful of OnLayout being called multiple times

    // otherwise, do some stuff here, set control sizes, etc.
}


AS far as I can remember the event order is something like

Form.Load
Form.Layout 
Form.VisibleChanged
Form.GotFocus
Form.Activated
Form.Shown

So if something is still happening after Form.Show it's because of the way you coded it.

Are you maybe creating the form dynamically?


The best solution is the Shown() event: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx

"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."


Try using Form.GotFocus (inherited from control).. something like this.

   private void Form1_Load(object sender, EventArgs e)
    {
        this.GotFocus += new EventHandler(Form1_gotFocus);
        this.Focus();
    }

    private void Form1_gotFocus(object sender, EventArgs e)
    {
      // You will need to Switch focus from form at the end of this function, 
      //to make sure it doesnt keep Firing.
    }

According To msdn , the following happens:

When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl..::.ActiveControl property to the current form, focus events occur in the following order:

  1. Enter
  2. GotFocus
  3. Leave
  4. Validating
  5. Validated
  6. LostFocus
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜