c# - 如何在 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。
解决方案
在我阅读了您的评论后,我建议对您的问题使用不同的方法。
使用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();
}
}));
}
}
}
推荐阅读
- git - 要推送当前分支并将远程设置为上游,请使用 git push --set-upstream origin master
- python - 如何使用循环而不是内置函数在 Python 中生成 Toeplitz 矩阵
- postgresql - PostgreSQL“时区日期”意外行为
- php - 如何访问 CURL 以从 php 获取 json 数据
- javascript - 将对象推送到多个循环内的数组
- alert - Rancher alertmanager 在使用 Webhook Notifier 时不断尝试连接 rancherlab(slack server)
- swift - 将翻译应用到根节点后第二次无法按预期工作
- javascript - 具有非 JSX 类的 React 功能组件具有返回未定义的内部数组
- json - 解码后如何访问 JSON 文件
- android - 禁用在 android 上显示 Paypal Web 浏览器