bool
бесполезен для такого делегата, обычно используется int
, потому что вам нужно 3 значения для представления результатов сравнения, меньше, равно и больше, чем. Коллекции .NET обычно (если не всегда) предполагают, что -1 означает меньше чем, 0 означает равный и 1 означает больше чем.
Затем вы должны в своем делегате проверить, является ли значение x меньше, равно или больше значения y. Интересно отметить, что если вы перевернете результаты, например, сравните y с x, то вы будете сортировать в противоположном направлении.
Чтобы упростить сортировку дат, проверьте ответ Джона Си или Сэма .
Как уже упоминали Башмохандес и Дмитрий Матвеев, решением должно быть FormClosingEventArgs. Но, как также сказал Дмитрий, это не повлияет на вашу кнопку и X в правом верхнем углу.
Чтобы различать эти две опции, вы можете добавить логическое свойство ExitButtonClicked к вашему form и установите для него значение true в кнопке Click-Event прямо перед вызовом Application.Exit ().
Теперь вы можете задать это свойство в событии FormClosing и различать эти два параметра в случае UserClosing .
Пример:
public bool UserClosing { get; set; }
public FormMain()
{
InitializeComponent();
UserClosing = false;
this.buttonExit.Click += new EventHandler(buttonExit_Click);
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void buttonExit_Click(object sender, EventArgs e)
{
UserClosing = true;
this.Close();
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.ApplicationExitCall:
break;
case CloseReason.FormOwnerClosing:
break;
case CloseReason.MdiFormClosing:
break;
case CloseReason.None:
break;
case CloseReason.TaskManagerClosing:
break;
case CloseReason.UserClosing:
if (UserClosing)
{
//what should happen if the user hitted the button?
}
else
{
//what should happen if the user hitted the x in the upper right corner?
}
break;
case CloseReason.WindowsShutDown:
break;
default:
break;
}
// Set it back to false, just for the case e.Cancel was set to true
// and the closing was aborted.
UserClosing = false;
}
Вы можете проверить свойство CloseReason объекта FormClosingEventArgs в обработчике событий FormClosing, чтобы проверить некоторые из возможных случаев. Однако описанные вами случаи будут неотличимы, если вы будете использовать только это свойство. Вам нужно будет написать дополнительный код в обработчике события нажатия кнопки «закрыть», чтобы сохранить некоторую информацию, которая будет проверяться в обработчике события FormClosing, чтобы различать эти случаи.
Вам нужно добавить слушателя к Even FormClosing, который отправляет в аргументах события свойство типа CloseReason, которое является одним из этих значений
// Summary:
// Specifies the reason that a form was closed.
public enum CloseReason
{
// Summary:
// The cause of the closure was not defined or could not be determined.
None = 0,
//
// Summary:
// The operating system is closing all applications before shutting down.
WindowsShutDown = 1,
//
// Summary:
// The parent form of this multiple document interface (MDI) form is closing.
MdiFormClosing = 2,
//
// Summary:
// The user is closing the form through the user interface (UI), for example
// by clicking the Close button on the form window, selecting Close from the
// window's control menu, or pressing ALT+F4.
UserClosing = 3,
//
// Summary:
// The Microsoft Windows Task Manager is closing the application.
TaskManagerClosing = 4,
//
// Summary:
// The owner form is closing.
FormOwnerClosing = 5,
//
// Summary:
// The System.Windows.Forms.Application.Exit() method of the System.Windows.Forms.Application
// class was invoked.
ApplicationExitCall = 6,
}