1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public partial class Form1 : Form
{
//On créé un timer de 2 secs
System.Timers.Timer myTimer = new System.Timers.Timer(2000);
public Form1()
{
InitializeComponent();
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
myTimer.Start();
}
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//On créé un second thread qui sera le thread de presentation de notre deuxieme form
Thread secondThreadGUI = new Thread(
delegate(object state)
{
//Nota : On est dans un thread du pool ici puisqu'on n'a pas assigné
//la propriété SynchronizingObject du timer
//On dispose le timer et ...
myTimer.Dispose();
// ... on invoque async le thread de la premiere form pour qu'elle se termine
this.BeginInvoke(new MethodInvoker(Dispose));
Form2 f = new Form2();
//On lance une boucle de message sur le thread courant (secondThreadGUI donc)
Application.Run(f);
});
//On le passe en STA (uniquement avant le lancement du thread)
//Cela fait exactement la meme chose que [STAThread] sur la method Main
secondThreadGUI.SetApartmentState(ApartmentState.STA);
//On le passe en thread foreground
secondThreadGUI.IsBackground = false;
secondThreadGUI.Start();
}
} |