title: Redirecting to another form in windows application c#
body: <p>I am using the below function to Close existing form and opening new form.
  I am getting the below error when the code tries to close the existing form</p>
  
  <p>Error :</p>
  
  <p>{System.InvalidOperationException: Cross-thread operation not valid: Control 'Screensaver' accessed from a thread other than the thread it was created on.</p>
  
  <p>Code :</p>
  
  <pre><code>   public static class Program
  {
      /// &lt;summary&gt;
      /// The main entry point for the application.
      /// &lt;/summary&gt;
      [STAThread]
      static void Main()
      {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          StartThread();
          Application.Run(new MyContext(new Screensaver()));
      }
      public class MyContext : ApplicationContext
      {
          static private Form curMain = null;
  
          public MyContext(Form main)
          {
              MyContext.NewMainForm(main, false);
          }
  
          static public void NewMainForm(Form main, bool ClosePreviousMain)
          {
              try
              {
                  if (main != null)
                  {
                      if (ClosePreviousMain &amp; MyContext.curMain != null)
                      {
                          MyContext.curMain.FormClosed -= new FormClosedEventHandler(main_FormClosed);
                          MyContext.curMain.Close();
                      }
  
                      MyContext.curMain = main;
                      MyContext.curMain.FormClosed += new FormClosedEventHandler(main_FormClosed);
                      MyContext.curMain.Show();
                  }
              }
              catch (Exception ex)
              {
                  ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Message :  " + ex.Message.ToString() + System.Environment.NewLine + "Stack :  " + ex.StackTrace.ToString());
              }
          }
  
          static private void main_FormClosed(object sender, FormClosedEventArgs e)
          {
              Application.Exit();
          }
  
      }
  </code></pre>