Windows Forms form opens in the background if I open OpenFileDialog in my Load event

I need a user to select the file to open before they can use the main form in the program I am writing. I wrote the following in a form load event handler:

private void MainForm_Load(object sender, EventArgs e)
{
    if (openXmlFileDialog.ShowDialog() != DialogResult.OK)
        Application.Exit();

    fileName = openXmlFileDialog.FileName;
    Activate();
}

After that, MainForm appears in the background, despite the call to the Activate () function on it.

Another problem is that if the user clicks Cancel and Application.Exit () is called, this does not affect.

+3
source share
2 answers

Put the code inside the event Shown.

+3
source

Do it in Program.cs

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    OpenFileDialog o = new OpenFileDialog();
    if (DialogResult.OK == o.ShowDialog())
    {
        Application.Run(new Form1(o.FileName));
    }
    else
    {
        Application.Exit();
    }
}

AT Form1.cs

string filename;
public Form1(string filename)
{
    this.filename=filename;
    InitializeComponent();
}
+1
source

Source: https://habr.com/ru/post/1780247/


All Articles