检测关闭 winform 时单击了哪个按钮?

Detecting which button was clicked when closing a winform?

我的 winform 中有这个事件处理程序:

private void SaveToDXF_FormClosing(object sender, FormClosingEventArgs e)
{
    // Make sure the user has selected at-least one layer
    if (listBoxLayers.SelectedItems.Count == 0)
    {
        _AcAp.Application.ShowAlertDialog("Please select one or more layers.");
        e.Cancel = true;
    }
}

最初我使用的是 OK 按钮单击处理程序,但我很快发现似乎没有办法取消实际关闭表单。然后我阅读了关于使用 FormClosing 的建议。这工作正常但是...

如果用户通过按 取消 按钮关闭表单,此事件仍会触发。这就说得通了。但我只想执行此验证检查并在他们单击 确定 按钮时取消关闭表单。

我们如何做到这一点?

听起来您可以检查关闭处理程序中的 this.DialogResult:它会有所不同,具体取决于单击的按钮(无论您在属性网格中设置什么 DialogResult)。

例如“如果他们正在取消,请不要检查”可能就像

if (this.DialogResult != DialogResult.Cancel && listBoxLayers.SelectedItems.Count == 0)

如果您有更多的检查要做,那么将“if cancelling then return”作为事件处理程序的第一行可能很简单