您如何只允许授权用户访问退出应用程序或关闭特定表单?

时间:2015-06-25 06:52:39

标签: c# winforms

我只需要允许其角色为“Admin”的用户退出application.I为此目的使用以下代码,但在传递消息后,应用程序正在终止。

private void Login_FormClosed(object sender, FormClosedEventArgs e)
{
    if (Login.role != "Admin")
    {
        MessageBox.Show("You are not authorized to Exit Application.");
    }
    else
    {
        Application.Exit();
    }
}

我也在FormClosing事件中使用它。但是没有正常运行。我正在使用c#windows应用程序。

4 个答案:

答案 0 :(得分:4)

使用FormClosing事件并尝试以下代码:

private void Login_FormClosing(object sender, FormClosingEventArgs e)
{
    if (Login.role != "Admin")
    {
        MessageBox.Show("You are not authorized to Exit Application.");
        e.Cancel = true;
    }
    else 
    {
        Application.Exit();
    }
}

答案 1 :(得分:3)

您需要添加:

e.Cancel = true;

if (Login.role != "Admin")部分。

您需要将此添加到FormClosing事件处理程序,而不是FormClosed事件处理程序。

答案 2 :(得分:2)

FormClosed事件为时已晚。使用FormClosing事件!你有e.Cancel,它可以帮助你取消关闭过程。

答案 3 :(得分:1)

添加FormClosing事件处理程序并将以下代码放入其中:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = Login.role != "Admin";
    }