在app启动时运行某个命令

时间:2017-09-22 20:55:22

标签: c#

我试图在程序启动时执行某些命令字符串,但它没有运行。我尝试了很多东西,但我的代码现在看起来与此类似

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO; 

namespace scriptname
{    
    public partial class Form1 : Form
    {
        public List<string> stringName = new List<string>();
        public int stringCount = 0;

        public Form1()
        {
            InitializeComponent();
        }

//this code needs to run on app startup.
//--------------------------------------------------------------------------
        public Awake()//this is from my knowledge with Unity
        {
            if (!Directory.Exists(@"C:\Example"))
            {
                Directory.CreateDirectory(@"C:\Example");
                StreamWriter exampleText = new StreamWriter(@"C:\Example\Example.txt");
            }
            else
                ReadFromFile();
        }
//--------------------------------------------------------------------------
    }
}

注意,我使用visual studio表单作为我的基础。

我试图让突出显示的文本在启动时运行,但每次检查时,文件夹都没有生成。我能想到的只是代码没有运行。

我真的不知道如何在启动时初始化它,我希望得到一些帮助。我可以按下按钮来运行它,但那么它的乐趣在哪里?

2 个答案:

答案 0 :(得分:3)

清醒是团结一致的东西。这不适用于Forms应用程序

public Form1()
{
    InitializeComponent();
    Awake(); // This will call awake when the form starts. Consider renaming it
}

public Form1()是此表单类的构造函数。加载表单时始终会调用它。每次运行此表单时,都会调用该方法。如果您只想运行一次代码而不管在运行时创建的表单的实例数,您应该将代码移动到默认Program.cs中的Main方法。

您也不应该在C:驱动器中保存或创建目录。您应该使用App数据文件夹。

答案 1 :(得分:2)

最好的方法是使用适当的事件来触发您想要的时间点。有一个事件实际上与Unity与它的Awake函数非常接近。它被称为OnLoad,只要Load事件发生(在第一次显示表单之前)就会运行

public partial class Form1 : Form
{

    public List<string> stringName = new List<string>();
    public int stringCount = 0;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e); //You must remember to call base.OnLoad(e) when you override

        if (!Directory.Exists(@"C:\Example"))
        {
            Directory.CreateDirectory(@"C:\Example");
            StreamWriter exampleText = new StreamWriter(@"C:\Example\Example.txt");
        }
        else
            ReadFromFile();
    }

}
相关问题