Hi,
there are few things, first of all you are doing all in a bundle, so you need to split them into tasks that does individual components such as:
1) Load First Form;
2) Start the Background worker to read the file, so that the form1 is responsive;
3) Read the file;
4) On background worker completed, invoke a delegate so that the resources are not caught in the cross thread operation;
5) process the results in the main thread;
6) initiate the second form;
7) show the new form;
8) hide the main form.
See code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace SecondFormOnFormLoad
{
public partial class Form1 : Form
{
private delegate void BGWorkerCompletedCallback();
private string _fileName = @"D:\Projects\VS_Test_Projects\CodeProjectTests\SecondFormOnFormLoad\bin\Debug\cfg.ini";
private string _errorMsg;
private List<string> _contentsOfIniFile;
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(500);
ReadFile();
}
private void ReadFile()
{
_errorMsg = null;
FileInfo fi = new FileInfo(_fileName);
if (!fi.Exists)
{
_errorMsg = "File doesn't exists!";
}
else
{
_contentsOfIniFile = new List<string>();
using (StreamReader sr = new StreamReader(_fileName, System.Text.Encoding.Default))
{
string str = "";
while ((str = sr.ReadLine()) != null)
{
_contentsOfIniFile.Add(str);
}
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BGWCompletedHandler();
}
private void BGWCompletedHandler()
{
new BGWorkerCompletedCallback(TaskCompleted).Invoke();
}
private void TaskCompleted()
{
if (_contentsOfIniFile.Count > 0)
{
CheckContentAndOpenNewForm();
}
else if (!string.IsNullOrEmpty(_errorMsg))
{
MessageBox.Show(_errorMsg);
}
}
private void CheckContentAndOpenNewForm()
{
string[] parts = _contentsOfIniFile[0].Split(new char[] { '=' });
if (parts.Length > 0)
{
if (parts[0].Contains("Hello World"))
{
Form2 frm = new Form2();
if (parts[1].Trim().Equals("1"))
{
frm.Show(this);
this.Hide();
}
}
}
}
}
}
This works like a sweet.
Regards
Jegan