user1434156
user1434156

Reputation:

Prompt user with an output file dialog at program startup (initialize)

I am currently working with output files. I am in the process of building a program that request for the user to save an output file before the program does anything else. The purpose is that the program will write results to this output file. I have been able to get the output file dialog to appear with a button click. Is there away to prompt the user with output file dialog as soon as the program initializes?

Code-output file through button:

namespace open_document
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Text Files | *.txt";
            openFile.ShowDialog();          
            StreamReader infile = File.OpenText(openFile.FileName);

        }

    }
}

Upvotes: 1

Views: 1247

Answers (4)

Adam Bruss
Adam Bruss

Reputation: 1674

This executes your code before the form loads.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Filter = "Text Files | *.txt";
        openFile.ShowDialog();          
        StreamReader infile = File.OpenText(openFile.FileName);
        ...

        Application.Run(new Form1());
    }
}

Upvotes: 1

KeithS
KeithS

Reputation: 71601

Your best option would probably be to extract the code from this handler into a method that takes no parameters (you don't need anything the event passes in anyway), and then call it in the constructor or Load event of the form.

Upvotes: 0

Furqan Safdar
Furqan Safdar

Reputation: 16728

Why don't you use the Load event of the Form or Page, as per your requirement:

Designer:

this.Load += new System.EventHandler(this.MainForm_Load);

Code:

private void MainForm_Load(object sender, EventArgs e)
{   
    OpenFileDialog openFile = new OpenFileDialog();
    openFile.Filter = "Text Files | *.txt";
    openFile.ShowDialog();          
    StreamReader infile = File.OpenText(openFile.FileName);
    // ... 
}

Upvotes: 1

user27414
user27414

Reputation:

You can use OnShown:

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    OpenFileDialog openFile = new OpenFileDialog();                 
    openFile.Filter = "Text Files | *.txt";                 
    openFile.ShowDialog();                           
    StreamReader infile = File.OpenText(openFile.FileName);   // Don't leave this open!
}

Upvotes: 0

Related Questions