Skip to main content
 首页 » 编程设计

c#之WinForm c# : Check first run and show message

2024年02月06日13lvdongjie

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

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

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

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

有什么想法吗?

请您参考如下方法:

除了从构造函数中调用 CheckFirstRun(),您还可以调用它 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(); 
} 

覆盖 OnShown

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

继承者须知 在派生类中覆盖 OnShown 时,一定要调用基类的 OnShown 方法,以便注册的委托(delegate)接收事件,MSDN .

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