简体   繁体   English

C#封闭事件和循环

[英]C# formclosing event and loops

If I have to declare a little bit more please tell me, it's a little bit late here. 如果我要多说一点,请告诉我,这里有点晚了。

I have a little problem, this code keeps looping :(... 我有一个小问题,这段代码不断循环:(...

I have this 我有这个

if (MessageBox.Show("Are you sure you want to quit?", "Confirm Quit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
    Stop();
    _exited = true;

    foreach (Process x in Process.GetProcesses())
    {
        while (x.Id == _processID)
        {
            Application.Exit();
            e.Cancel = true;
            return;
        }
    }
}

Description 描述

It keeps looping because you call Application.Exit() inside this method. 因为您在此方法内调用Application.Exit()所以它一直在循环。 I dont know what you trying to do but i think you want to ask the user if he really wants close the app. 我不知道您要做什么,但我想您想问一下用户是否真的要关闭该应用程序。 If your set e.Cancel = true it means you cancel the event, so in your case you cancel to close the app. 如果您将e.Cancel = true设置e.Cancel = true则意味着您取消了该事件,因此在您的情况下,您将取消以关闭该应用程序。

So if your ask "sure you want to quit" and user choose "No" you should set e.Cancel = true , if not do nothing because the default value of e.Cancel is false . 因此,如果您询问“确定要退出”并且用户选择“否”,则应将e.Cancel = true设置e.Cancel = true ,如果不执行任何操作则因为e.Cancel的默认值为false

Sample 样品

// create a list of process
private List<Process> processes = new List<Process>();

// if you start a process
Process myProcess = //;
processes.Add(myProcess);

// on closing
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    var isAProcessRunning = processes.Where(p => p.HasExited == false);

    if (isAProcessRunning.Any()) 
    {
      // some process is already running, ask the user 

        if (MessageBox.Show("Are you sure you want to quit?", "Confirm Quit", MessageBoxButtons.YesNo) ==
        DialogResult.No)
        {
            e.Cancel = true;
        }
     }
  }

More Information 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM