8

I have a problem similar to this one: How can I execute code after my form starts?

But the solution there won't work for me because I am not running a form, I'm running a single custom control, which is a tray icon that monitors things. (Similar to the Icon Dropbox has, where that is the only interface the user has with the program)

What should I do to run code when the control is created? (which has to be after the message pump starts)

Community
  • 1
  • 1
Drew
  • 12,578
  • 11
  • 58
  • 98

2 Answers2

5

I think you're looking for the Application.Idle event.

Occurs when the application finishes processing and is about to enter the idle state.

E.g.

Application.Idle += delegate { Console.WriteLine(Application.MessageLoop); };

// Output: true 
Application.Run();
Ani
  • 111,048
  • 26
  • 262
  • 307
  • 1
    Thanks thats exactly what I was looking for. I'll just need to make sure it only runs the first time its called and it will be perfect. I guess I'll just remove that delegate when I'm done. – Drew Mar 06 '11 at 20:52
  • This will be called a myriad times, not once. – John Nov 09 '22 at 03:40
  • @John: You can always unsubscribe from the event from within the handler to make it one-shot. – Ani Nov 09 '22 at 15:02
  • @Ani okay, you should add that into your answer code Anyone who reads this question and answer is likely totally new to C-Sharp, so unsubscribing from a Idle event is not the first thing that comes into a newbies mind. – John Nov 09 '22 at 16:43
4

First option would be to post a windows message to yourself. That way it will not be dispatched until your thread starts pumping messages. A second option is to hook into the Application.Idle event which is fired when the message queue is empty. Your third option would be to set and run a Timer for a small duration and hook into the Tick event for when it expires. Fourth and the last for now is to fire a delegate asynchronously as they use the message queue as the mechanism for being fired.

Phil Wright
  • 22,580
  • 14
  • 83
  • 137