首页 > 解决方案 > 如何在 c# Winforms 中从另一个窗体中捕获或获取 e.cancel 属性

问题描述

我想知道如何使用 Form_Closing 事件处理程序关闭两个表单。

例子:

主窗体;

MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
var d = (MessageBox.Show("Exit Program","Confirm",MessageBoxButton.YesNo,MessageBoxIcon.Question);
    if(d== DialogResult.Yes)
   {
     e.cancel=false;
   }
     else
   {
     e.cancel=true;
   }

}

在另一种形式中称为 LoginForm;

LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
   var f = (MainForm)Application.OpenForms["MainForm"];
   if(f!=null)
   {
      if(f==DialogResult.Yes)
    Application.Exit();
   }

}

我的问题是如何在 MainForm 中调用 e.cancel 函数,以便可以覆盖 FormClosing e.cancel=false 并使用 Application.Exit(); 关闭应用程序 从登录表单

LoginForm 是一个模态对话框,它的父级是 MainForm。

标签: c#winformsmodal-dialogeventhandlerformclosing

解决方案


在我阅读了您的评论后,我建议对您的问题使用不同的方法。
使用DialogResult登录表单的属性来指示应用程序是否应该终止,这是一个示例,此代码应在 MainForm 上运行。

注意:这是一个基本示例,可能需要根据您的项目进行一些修改,例如检查是否有一些较长的进程正在运行,并且在进程完成后应该延迟和调用表单......

请阅读示例中的注释:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        // Start the measuring time for reauthentication
        StartReAuthTimer();
    }

    // The session allowed time
    private const int AllowedSessionSecconds = 30*60;
    // Timer to check if user passed the allowed time
    private System.Timers.Timer ReAuthTimer;
    // holds the beginning of session time 
    DateTime LastSessionBeginTime;
    // indicates if the login form is open
    private bool IsLoginFormShown = false;

    private void StartReAuthTimer()
    {
        if (ReAuthTimer == null)
        {
            ReAuthTimer = new System.Timers.Timer();
        }
        IsLoginFormShown = false;
        ReAuthTimer.Interval = 10000;
        LastSessionBeginTime = DateTime.Now;
        ReAuthTimer.Elapsed += ReAuthTimer_Elapsed;
        ReAuthTimer.Start();
    }

    private void CancelTimer()
    {
        ReAuthTimer.Elapsed -= ReAuthTimer_Elapsed;
        ReAuthTimer.Dispose();
        ReAuthTimer = null;
    }

    private void ReAuthTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (DateTime.Now >= LastSessionBeginTime.AddSeconds(AllowedSessionSecconds) && IsLoginFormShown == false)
        {              
            // ReAuthenticate
            IsLoginFormShown = true;
            CancelTimer();
            LoginForm login = new LoginForm();
            // Show the login form, note: because we are running on the main thread we will use Invoke()
            this.Invoke(new Action(() =>
            {
                DialogResult result = login.ShowDialog();
                if (result == DialogResult.Cancel)
                {
                    // The user closed the form
                    Application.Exit();
                }
                else
                {
                    // Authenticated succesfuly - start timer again
                    StartReAuthTimer();
                }
            }));
            
        }
    }
}

推荐阅读