简体   繁体   中英

WinForm c#: Check first run and show message

I am creating a winform application containing first run check. I've been following these 2 articles:

First run check is supposed to check if application has ever been run and if not, it should show some message to the user. Problem i am having is, that this message is displayed before winform application is initialized/displayed and I am not able to find out why. Here is my code:

Program.cs

public static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

Form1.cs

public Form1()
{
    this.InitializeComponent();
    CheckFirstRun();
}

private static void CheckFirstRun()
{
    if(Settings.Default.FirstRun)
    {
        MessageBox.Show(
            "First run");
        Settings.Default.FirstRun = false;
        Settings.Default.Save();
}

It shows Message box with msg: "First run" and after clicking OK button it shows WinForm. What I am trying to achieve is to Display WinForm first and if it is first run then show this msgBox.

Any ideas?

Instead of calling CheckFirstRun() from constructor you can call it Form.Shown

Form.Shown Event

The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event

private void Form1_Shown(Object sender, EventArgs e) 
{
    CheckFirstRun();
}

Overriding OnShown

The OnShown method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class, MSDN

Notes to Inheritors When overriding OnShown in a derived class, be sure to call the base class's OnShown method so that registered delegates receive the event, MSDN .

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    CheckFirstRun();
}

Call CheckFirstRun from OnShown method.

The Shown event occurs whenever the form is first shown.

[...]

The OnShown method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

public Form1()
{
    this.InitializeComponent();
}

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    CheckFirstRun();
}

private static void CheckFirstRun()
{
    if(Settings.Default.FirstRun)
    {
        MessageBox.Show(
            "First run");
        Settings.Default.FirstRun = false;
        Settings.Default.Save();
    }
}

Use this event to fire the event after form has load.

private void Form1_Shown(Object sender, EventArgs e) {

MessageBox.Show("First run.");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM