c# - 关闭我的应用程序会干扰我的 Form1_FormClosing 事件

标签 c# try-catch sqlconnection formclosing

在表单加载时,我试图查看我的应用程序是否可以连接到数据库。如果它没有连接,我想显示一个带有好消息的消息框,然后关闭应用程序。我遇到的问题是,当它尝试关闭应用程序时,它会遇到 Form_looking 事件,询问他们“是否要退出应用程序”,对于无权访问应用程序的用户来说,这看起来有点奇怪/数据库来查看消息框。我只想跳过表单关闭事件并关闭表单,任何帮助将不胜感激。

  private void Form1_Load(object sender, EventArgs e)
  {
     checkcon();
  }
  private void checkcon()
  {
     try
     {
       MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);
       con.Open();
       con.Close();
     }
     catch (Exception ex)
     {
       MessageBox.Show("Your domain account does not have sufficient privilages to    continue with the application please contact the IS support Team.");              
       Close();
     }

  }

  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
    DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
     if (result == DialogResult.No)
     {
        e.Cancel = true;
     }
     else
     {
     }
  }

最佳答案

添加一个静态 bool 变量作为检查是否显示对话:

 public static bool HasPermission=true;
 private void checkcon()
  {
     try
     {
       MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);
       con.Open();

       con.Close();
     }
     catch (Exception ex)
     { 
       HasPermission=false;
       MessageBox.Show("Your domain account does not have sufficient privilages to    continue with the application please contact the IS support Team.");              
       Close();
     }

  }

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  { if (HasPermission)
    {
    DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
     if (result == DialogResult.No)
     {
        e.Cancel = true;
     }
     else
     {
     }
     }
  }

关于c# - 关闭我的应用程序会干扰我的 Form1_FormClosing 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587462/

相关文章:

javascript - 抛出异常时不要停止 JavaScript

php - 简单的 try/finally 与 try/catch

java - java对话中未捕获空指针异常

.net - 检测是否调用了垃圾收集器(.Net)

c# - SqlDataReader 的 Connection 属性为 Null

c# - 将数组的 JSON 数组反序列化为 c# 类

c# - Datagrid中删除行

c# - 使用 sql 身份验证的 sql 连接字符串

c# - DataTable排序时如何区分大小写?

c# - 使用 BrowserSession 和 HtmlAgilityPack 通过 .NET 登录 Facebook