How do I execute code AFTER a form has loaded?

86

Solution 1

You could use the "Shown" event: MSDN - Form.Shown

"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."

Solution 2

I sometimes use (in Load)

this.BeginInvoke((MethodInvoker) delegate {
  // some code
});

or

this.BeginInvoke((MethodInvoker) this.SomeMethod);

(change "this" to your form variable if you are handling the event on an instance other than "this").

This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.

[updated on request]

The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.

Normally, these would be used as:

SomeCodeOrEventHandlerOnAWorkerThread()
{
  // this code running on a worker thread...
  string newText = ExpensiveMethod(); // perhaps a DB/web call

  // now ask the UI thread to update itself
  this.Invoke((MethodInvoker) delegate {
      // this code runs on the UI thread!
      this.Text = newText;
  });
}

It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p

OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...

But Control.BeginInvoke works differently: it always pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).

Solution 3

First time it WILL NOT start "AfterLoading",
It will just register it to start NEXT Load.

private void Main_Load(object sender, System.EventArgs e)
{
    //Register it to Start in Load 
    //Starting from the Next time.
    this.Activated += AfterLoading;
}

private void AfterLoading(object sender, EventArgs e)
{
    this.Activated -= AfterLoading;
    //Write your code here.
}

Solution 4

I had the same problem, and solved it as follows:

Actually I want to show Message and close it automatically after 2 second. For that I had to generate (dynamically) simple form and one label showing message, stop message for 1500 ms so user read it. And Close dynamically created form. Shown event occur After load event. So code is

Form MessageForm = new Form();
MessageForm.Shown += (s, e1) => { 
    Thread t = new Thread(() => Thread.Sleep(1500)); 
    t.Start(); 
    t.Join(); 
    MessageForm.Close(); 
};

Solution 5

You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.

Share:
86
user3318525
Author by

user3318525

Updated on May 09, 2021

Comments

  • user3318525
    user3318525 about 3 years
    if($sql = $db->query("Count (*) FROM post_items")){
            echo mysqli_num_rows($sql);
    }
    

    what's wrong with my code? is this the correct way to echo the total of row in a table?

    • M Khalid Junaid
      M Khalid Junaid about 10 years
      Missing SELECT in your query try this SELECT Count(*) FROM post_items
    • user3318525
      user3318525 about 10 years
      @MKhalidJunaid didn't work too
    • Dharman
      Dharman about 4 years
      Does this answer your question? MySQLi count(*) always returns 1
  • Torbjørn
    Torbjørn over 15 years
    Did not completely understand that one. Can you explain a bit more?
  • huMpty duMpty
    huMpty duMpty almost 12 years
    Hi mark, is it possible to make form responsive while the process complete which is called in BeginInvoke ??
  • ckonig
    ckonig over 11 years
    To me it seems like the shown handler is executed WHILE the form is loading... am i wrong?
  • Dennis Ziolkowski
    Dennis Ziolkowski over 10 years
    Old but gold... Yes, you are wrong. GUI can not run parallel tasks, what is important to do something WHILE another execution is done.
  • user3318525
    user3318525 about 10 years
    then that's not what I want. I need to know the total row in the table. like 50 customers has bought an item.
  • Deepika Janiyani
    Deepika Janiyani about 10 years
    echoing the count will do that for you, mysqli_num_rows returns no of rows not the data of rows
  • Deepika Janiyani
    Deepika Janiyani about 10 years
    to get data you will have to fetch the result and then display it, check updated ans
  • Artemix
    Artemix over 9 years
    If in Load event handler there is a code that calls Application.DoEvents(), the Shown event fires before Load event handlers finished their execution. This is because Shown event is in fact put in a message queue using Form.BeginInvoke(ShownEvent) and DoEvents() forces it to fire before Load finishes.
  • ocramot
    ocramot almost 9 years
    It was not enough not work for me, in C#. I had to add Shown += Form1_Shown; as suggested in another thread
  • Dev.Jaap
    Dev.Jaap about 8 years
    In my case, the Shown-event did show a proper loaded form after I called Application.DoEvents() before I started the proces.
  • Aylian Craspa
    Aylian Craspa almost 8 years
    you should add This.Refresh(); inside the Shown event first before your logic and it will hold and refresh the form to fully loaded before your logic start running
  • dthor
    dthor over 7 years
    @AylianCraspa Thanks, that's exactly what I was missing. It's important especially if you're acting on an object within the form. For example, filling in text to a TextBox.
  • Victor_Tlepshev
    Victor_Tlepshev over 6 years
    In my case I want to print the form as soon as it finishes loading all the data on the screen and then close it. Shown does not help. Any ideas why?
  • Matthias Schippling
    Matthias Schippling over 6 years
    @Victor: I suggest opening a new question for that and to provide more information regarding what exactly you are expecting, what is not working and what you tried already. The comments are not a good place to do that.
  • Victor_Tlepshev
    Victor_Tlepshev over 6 years
    I agree Matthias. However, I can not post questions. I found this thread related to my problem. So I tried giving it a shot.
  • mrid
    mrid about 5 years
    what is it's equivalent in WPF ?
  • Steve Smith
    Steve Smith over 4 years
    This seems incredibly long-winded, and does it have any advantages over simply catching the Shown event?
  • Daniel
    Daniel almost 4 years
    However the Shown event is only useful for Forms, but not for Controls etc. in case you need that aswell
  • Ruslan
    Ruslan almost 3 years
    Here's a beginner-friendly example of how to use Shown: Define a method private void Form1_Shown(). Put any other methods inside this method to run on shown. Then call the Form1_Shown method inside the Form1(), right after the InitializeComponent().
  • Peyman Majidi
    Peyman Majidi over 2 years
    best answer here <----