WinForm c#:检查第一次运行并显示消息 [英] WinForm c#: Check first run and show message

查看:33
本文介绍了WinForm c#:检查第一次运行并显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个包含首次运行检查的 winform 应用程序.我一直在关注这两篇文章:

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

首次运行检查应该检查应用程序是否曾经运行过,如果没有,它应该向用户显示一些消息.我遇到的问题是,此消息显示之前 winform 应用程序初始化/显示,我无法找出原因.这是我的代码:

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:

程序.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();
}

它显示带有 msg 的消息框:首次运行",单击确定"按钮后显示 WinForm.我想要实现的是首先显示 WinForm,如果它是第一次运行,则显示此 msgBox.

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.

有什么想法吗?

推荐答案

不是从构造函数中调用 CheckFirstRun() 你可以调用它 Form.Shown

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

表单.显示事件

Shown 事件仅在第一次显示表单时引发;随后最小化、最大化、恢复、隐藏、显示或失效和重绘不会引发此事件

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

覆盖 OnShown

OnShown 方法还允许派生类在不附加委托的情况下处理事件.这是在派生类中处理事件的首选技术,MSDN

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

给继承人的注意事项在派生类中重写 OnShown 时,请务必调用基类的 OnShown 方法,以便注册的委托接收事件,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();
}

这篇关于WinForm c#:检查第一次运行并显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆