1

我目前正在处理输出文件。我正在构建一个程序,该程序要求用户在程序执行任何其他操作之前保存输出文件。目的是程序将结果写入此输出文件。我已经能够通过单击按钮来显示输出文件对话框。程序初始化后是否会立即通过输出文件对话框提示用户?

通过按钮的代码输出文件:

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);

        }

    }
}
4

4 回答 4

2

根据您的要求,您为什么不使用or的Load事件:FormPage

设计师:

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

代码:

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);
    // ... 
}
于 2012-10-23T17:50:46.653 回答
1

这会在表单加载之前执行您的代码。

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());
    }
}
于 2012-10-23T18:29:04.133 回答
0

您可以使用 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!
}
于 2012-10-23T17:50:36.353 回答
0

您最好的选择可能是将此处理程序中的代码提取到不带参数的方法中(无论如何您不需要事件传递的任何内容),然后在构造函数或表单的 Load 事件中调用它。

于 2012-10-23T17:50:47.833 回答