C#: как узнать, что пользователь кликнул на кнопку ‘X’ формы?
Добавил(а) microsin
Задача — определить разные источники действий пользователя, которые приводят к закрытию формы. Например, пользователь может кликнуть на стандартной кнопке с крестиком X (которая находится в правом верхнем углу окна, на плашке), либо он может кликнуть на отдельной кнопке пользователя, обработчик которой закрывает форму.
[Событие FormClosing]
Если используются WinForms, то можно использовать событие FormClosing(). Оно срабатывает всякий раз, когда форма закрывается. Чтобы детектировать действие пользователя, когда он кликнул либо на стандартной кнопке X либо на Вашей кнопке CloseButton, можно получить информацию через объект sender. Попробуйте привести тип источника события (cast sender) как управляющий элемент кнопки (Button control), и проверьте эго имя — к примеру, равно ли оно «CloseButton».
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (string.Equals((sender as Button).Name, @"CloseButton")) { // Действия, соответствующие CloseButton. ... } else { // Другие действия, которые приводят к закрытию формы. // Предположительно пользователь кликнул на кнопку 'X'. ... } }
Закрытие формы комбинацией клавиш ALT+F4 также приведет к вызову события FormClosing(), поскольку это связано с отправкой сообщения закрытия для формы. Вы можете отменить действие события закрытия формы, если присвоите FormClosingEventArgs.Cancel = true.
Для нашего примера достаточно вставить в обработчик Form1_FormClosing следующий код:
Обратите внимание на различие между событиями FormClosing() и the FormClosed(). FormClosing происходит, когда форма приняла сообщение для закрытия, и в обработчике FormClosing можно выполнить некоторые действия, которые произойдут перед закрытием формы и уничтожением его экземпляра класса (в частности, можно отменить закрытие формы, как мы сделали в предыдущем примере). Событие FormClosed происходит, когда форма по-настоящему закрыта, т. е. здесь можно выполнить действия, которые произойдут после закрытия формы.
[CloseReason]
Перечисление CloseReason, описание которого можно найти в MSDN, позволяет определить, каким образом пользователем было закрыто приложение — либо при выключении компьютера, либо через Диспетчер Задач (task manager), и т. д. Чтобы дифференцировать друг от друга причины закрытия, можно использовать примерно такой код:
void Form_FormClosing(object sender, FormClosingEventArgs e) { if(e.CloseReason == CloseReason.UserClosing) { // Приложение закрыл пользователь, можно предложить ему сохранить данные ... } if(e.CloseReason == CloseReason.WindowsShutDown) { // Автосохранение и очистка ресурсов ... } }
Однако в этом коде нет различий между кликом на кнопке x, правым кликом на плашке и выбором в контекстном меню «Закрыть», нажатием Alt+F4, и т. п. Все это действия пользователя, так что они будут соответствовать CloseReason.UserClosing.
[DialogResult]
Кнопка «X» соответствует DialogResult.Cancel, так что это дополнительная возможность оценки результата закрытия диалога. Если на форме есть несколько кнопок, то возможно Вы можете захотеть связать разные DialogResult с каждой, и это даст дополнительную информацию для того, чтобы отличать кнопки друг от друга. Например: btnSubmit.DialogResult = DialogResult.OK, btnClose.DialogResult = Dialogresult.Abort, и т. п.
public Form1() { InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
/// < summary >
/// Переопределение события Close для формы
/// < /summary >
/// < param name="sender" >< /param >
/// < param name="e" >< /param >
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) { //В случае, когда Windows завершает работу, мы не будем управлять процессом: if (e.CloseReason == CloseReason.WindowsShutDown) return;
if (this.DialogResult == DialogResult.Cancel) { // Предположим, что кликнули на X, и выполним соответствующие действия. // Выдача запроса подтверждения пользователю: switch (MessageBox.Show(this, "Вы уверены?", "Действительно хотите ... ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { case DialogResult.No: // Остаемся в этой форме e.Cancel = true; break; default: break; } } }
[Ссылки]
1. How to know user has clicked X or the Close button site:stackoverflow.com.
Распределенное обучение с TensorFlow и Python
AI_Generated 05.05.2025
В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .
CRUD API на C# и GraphQL
stackOverflow 05.05.2025
В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
- September 9, 2022
- PHP
- Form.Closing Event
- Windows Forms in C# cancel event
- Form.Closing Event
- Form.FormClosing Event
- Form.Closed Event
- Form.OnClosing(CancelEventArgs) Method
- How to suspend events when setting a property of a WinForms control
- How to handle a control event (Windows Forms .NET)
- C# windows forms cancel event
Form.Closing Event
People also askHow do I cancel a formclosing event?How do I cancel a
formclosing event?The FormClosingevent occurs as the form is being closed.
When a form is closed, it is disposed, releasing all resources associated with
the form. If you cancel this event, the form remains opened. To cancel the
closure of a form, set the Cancelproperty of the FormClosingEventArgspassed to
your event handler to true.Form.FormClosing Event (System.Windows.Forms)
Microsoft Docs
public:
event System::ComponentModel::CancelEventHandler ^ Closing;
public event System.ComponentModel.CancelEventHandler Closing;
[System.ComponentModel.Browsable(false)]
public event System.ComponentModel.CancelEventHandler Closing;
[System.ComponentModel.Browsable(false)]
public event System.ComponentModel.CancelEventHandler? Closing;
member this.Closing : System.ComponentModel.CancelEventHandler
[<System.ComponentModel.Browsable(false)>]
member this.Closing : System.ComponentModel.CancelEventHandler
Public Custom Event Closing As CancelEventHandler
private:
void Form1_Closing( Object^ /*sender*/, System::ComponentModel::CancelEventArgs^ e )
{
// Determine if text has changed in the textbox by comparing to original text.
if ( textBox1->Text != strMyOriginalText )
{
// Display a MsgBox asking the user to save changes or abort.
if ( MessageBox::Show( "Do you want to save changes to your text?", "My Application", MessageBoxButtons::YesNo ) == ::DialogResult::Yes )
{
// Cancel the Closing event from closing the form.
e->Cancel = true;
// Call method to save file...
}
}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
Private Sub Form1_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
' Determine if text has changed in the textbox by comparing to original text.
If textBox1.Text <> strMyOriginalText Then
' Display a MsgBox asking the user to save changes or abort.
If MessageBox.Show("Do you want to save changes to your text?", "My Application", MessageBoxButtons.YesNo) = DialogResult.Yes Then
' Cancel the Closing event from closing the form.
e.Cancel = True
End If ' Call method to save file...
End If
End Sub
End Class
Windows Forms in C# cancel event
By making e.Cancel = true;, you are telling the grid to not let the cell lose
focus, but the MessageBox makes the cursor leave the control. Things go a
little haywire. Things go a little haywire. The coloring part should be
working, but because the cell is highlighted, you probably aren’t seeing the
result.
private void dataInventory_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
switch (e.ColumnIndex)
{
case 0:
if (!Utilities.validName(e.FormattedValue))
{
dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
MessageBox.Show("The value entered is not valid.");
e.Cancel = true;
}
else
{
dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
}
break;
dataGridView1.Rows[e.RowIndex].ErrorText = "Fix this";
e.Cancel = true;
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Red;
dataInventory.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
Form.Closing Event
public:
event System::ComponentModel::CancelEventHandler ^ Closing;
public event System.ComponentModel.CancelEventHandler Closing;
[System.ComponentModel.Browsable(false)]
public event System.ComponentModel.CancelEventHandler Closing;
[System.ComponentModel.Browsable(false)]
public event System.ComponentModel.CancelEventHandler? Closing;
member this.Closing : System.ComponentModel.CancelEventHandler
[<System.ComponentModel.Browsable(false)>]
member this.Closing : System.ComponentModel.CancelEventHandler
Public Custom Event Closing As CancelEventHandler
private:
void Form1_Closing( Object^ /*sender*/, System::ComponentModel::CancelEventArgs^ e )
{
// Determine if text has changed in the textbox by comparing to original text.
if ( textBox1->Text != strMyOriginalText )
{
// Display a MsgBox asking the user to save changes or abort.
if ( MessageBox::Show( "Do you want to save changes to your text?", "My Application", MessageBoxButtons::YesNo ) == ::DialogResult::Yes )
{
// Cancel the Closing event from closing the form.
e->Cancel = true;
// Call method to save file...
}
}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
Private Sub Form1_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
' Determine if text has changed in the textbox by comparing to original text.
If textBox1.Text <> strMyOriginalText Then
' Display a MsgBox asking the user to save changes or abort.
If MessageBox.Show("Do you want to save changes to your text?", "My Application", MessageBoxButtons.YesNo) = DialogResult.Yes Then
' Cancel the Closing event from closing the form.
e.Cancel = True
End If ' Call method to save file...
End If
End Sub
End Class
Form.FormClosing Event
To cancel the closure of a form, set the Cancel property of the
FormClosingEventArgs passed to your event handler to true. When a form is
displayed as a modal dialog box, clicking the Close button (the button with an
X at the upper-right corner of the form) causes the form to be hidden and the
DialogResult property to be set to DialogResult.Cancel .
public:
event System::Windows::Forms::FormClosingEventHandler ^ FormClosing;
public event System.Windows.Forms.FormClosingEventHandler FormClosing;
public event System.Windows.Forms.FormClosingEventHandler? FormClosing;
member this.FormClosing : System.Windows.Forms.FormClosingEventHandler
Public Custom Event FormClosing As FormClosingEventHandler
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("{0} = {1}", "CloseReason", e.CloseReason );
messageBoxCS.AppendLine();
messageBoxCS.AppendFormat("{0} = {1}", "Cancel", e.Cancel );
messageBoxCS.AppendLine();
MessageBox.Show(messageBoxCS.ToString(), "FormClosing Event" );
}
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
Dim messageBoxVB as New System.Text.StringBuilder()
messageBoxVB.AppendFormat("{0} = {1}", "CloseReason", e.CloseReason)
messageBoxVB.AppendLine()
messageBoxVB.AppendFormat("{0} = {1}", "Cancel", e.Cancel)
messageBoxVB.AppendLine()
MessageBox.Show(messageBoxVB.ToString(),"FormClosing Event")
End Sub
Form.Closed Event
To prevent a form from closing, handle the Closing event and set the Cancel
property of the CancelEventArgs passed to your event handler to true. You can
use this event to perform tasks such as freeing resources used by the form and
to save information entered in the form or to update its parent form.
public:
event EventHandler ^ Closed;
public event EventHandler Closed;
[System.ComponentModel.Browsable(false)]
public event EventHandler Closed;
[System.ComponentModel.Browsable(false)]
public event EventHandler? Closed;
member this.Closed : EventHandler
[<System.ComponentModel.Browsable(false)>]
member this.Closed : EventHandler
Public Custom Event Closed As EventHandler
static int x = 200;
static int y = 200;
void Button1_Click( System::Object^ sender, System::EventArgs^ e )
{
// Create a new Form1 and set its Visible property to true.
Form1^ form2 = gcnew Form1;
form2->Visible = true;
// Set the new form's desktop location so it
// appears below and to the right of the current form.
form2->SetDesktopLocation( x, y );
x += 30;
y += 30;
// Keep the current form active by calling the Activate
// method.
this->Activate();
this->Button1->Enabled = false;
}
// Updates the label text to reflect the current values of x
// and y, which was were incremented in the Button1 control's
// click event.
void Form1_Activated( Object^ sender, System::EventArgs^ e )
{
Label1->Text = String::Format( "x: {0} y: {1}", x, y );
Label2->Text = String::Format( "Number of forms currently open: {0}", count );
}
static int count = 0;
void Form1_Closed( Object^ sender, System::EventArgs^ e )
{
count -= 1;
}
void Form1_Load( Object^ sender, System::EventArgs^ e )
{
count += 1;
}
static int x = 200;
static int y = 200;
private void Button1_Click(System.Object sender,
System.EventArgs e)
{
// Create a new Form1 and set its Visible property to true.
Form1 form2 = new Form1();
form2.Visible = true;
// Set the new form's desktop location so it
// appears below and to the right of the current form.
form2.SetDesktopLocation(x, y);
x += 30;
y += 30;
// Keep the current form active by calling the Activate
// method.
this.Activate();
this.Button1.Enabled = false;
}
// Updates the label text to reflect the current values of x
// and y, which was were incremented in the Button1 control's
// click event.
private void Form1_Activated(object sender, System.EventArgs e)
{
Label1.Text = "x: "+x+" y: "+y;
Label2.Text = "Number of forms currently open: "+count;
}
static int count = 0;
private void Form1_Closed(object sender, System.EventArgs e)
{
count -= 1;
}
private void Form1_Load(object sender, System.EventArgs e)
{
count += 1;
}
Shared x As Integer = 200
Shared y As Integer = 200
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' Create a new Form1 and set its Visible property to true.
Dim form2 As New Form1
form2.Visible = True
' Set the new form's desktop location so it appears below and
' to the right of the current form.
form2.SetDesktopLocation(x, y)
x += 30
y += 30
' Keep the current form active by calling the Activate method.
Me.Activate()
Me.Button1.Enabled = False
End Sub
' Updates the label text to reflect the current values of x and y,
' which was were incremented in the Button1 control's click event.
Private Sub Form1_Activated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Activated
Label1.Text = "x: " & x & " y: " & y
Label2.Text = "Number of forms currently open: " & count
End Sub
Shared count As Integer = 0
Private Sub Form1_Closed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Closed
count -= 1
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
count += 1
End Sub
Form.OnClosing(CancelEventArgs) Method
The following example uses Closing to test if the text in a TextBox has
changed. If it has, the user is asked whether to save the changes to a file.
C#. Copy. private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e) { // Determine if text has changed in
the textbox by comparing to original text. if (textBox1.Text !=
strMyOriginalText) { // Display a …
protected:
virtual void OnClosing(System::ComponentModel::CancelEventArgs ^ e);
protected virtual void OnClosing (System.ComponentModel.CancelEventArgs e);
abstract member OnClosing : System.ComponentModel.CancelEventArgs -> unit
override this.OnClosing : System.ComponentModel.CancelEventArgs -> unit
Protected Overridable Sub OnClosing (e As CancelEventArgs)
private:
void Form1_Closing( Object^ /*sender*/, System::ComponentModel::CancelEventArgs^ e )
{
// Determine if text has changed in the textbox by comparing to original text.
if ( textBox1->Text != strMyOriginalText )
{
// Display a MsgBox asking the user to save changes or abort.
if ( MessageBox::Show( "Do you want to save changes to your text?", "My Application", MessageBoxButtons::YesNo ) == ::DialogResult::Yes )
{
// Cancel the Closing event from closing the form.
e->Cancel = true;
// Call method to save file...
}
}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
Private Sub Form1_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
' Determine if text has changed in the textbox by comparing to original text.
If textBox1.Text <> strMyOriginalText Then
' Display a MsgBox asking the user to save changes or abort.
If MessageBox.Show("Do you want to save changes to your text?", "My Application", MessageBoxButtons.YesNo) = DialogResult.Yes Then
' Cancel the Closing event from closing the form.
e.Cancel = True
End If ' Call method to save file...
End If
End Sub
End Class
How to suspend events when setting a property of a WinForms control
b) Use a custom flag indicating whether or not to execute event handlers. This
must be checked within every involved handler manually. By the framework
supported solution as with (b) or a method pair aka SuspendLayout (),
ResumeLayout (bool) designed to suspend all custom events would be what I’m
looking for.
private void button1_Click(object sender, EventArgs e)
{
EventSuppressor oES = new EventSuppressor(checkBox1);
oES.Suppress();
checkedListBox1.SetItemChecked(0, checkedListBox1.CheckedItems.Count == 0);
oES.Resume();
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
MessageBox.Show("checkedListBox1_ItemCheck");
}
public class MyForm: Form
{
private bool disableField;
public partial class MyForm()
{
// assume it contains a numericUpDown
NumericUpDown numericUpDownField;
numericUpDownField.ValueChanged += new System.EventHandler(this.numericUpDownField_ValueChanged);
disableField = false;
}
public void SetInitialValues()
{
// disable event
disableField = true;
// set value
numericUpDownField.Value = 100;
// enable event
disableField = false;
}
void numericUpDownField_ValueChanged(object sender, EventArgs e)
{
// jump out when disabled
if (disableField) return
// write to database
write();
}
}
public class MyForm: Form
{
private List<object> disabledFields;
public partial class MyForm()
{
// assume it contains a numericUpDown
NumericUpDown numericUpDownField;
numericUpDownField.ValueChanged += new System.EventHandler(this.numericUpDownField_ValueChanged);
disabledFields = new List<object>();
}
public void SetInitialValues()
{
// Add to list to disable ONCE
disabledFields.Add(numericUpDownField);
// set value
numericUpDownField.Value = 100;
}
void numericUpDownField_ValueChanged(object sender, EventArgs e)
{
// jump out when disabled, but remove entry before exiting
if (disabledFields.contains(sender))
{
disabledFields.remove(sender);
return
}
// write to database
write();
}
}
public class EventSuspender
{
private List<object> disabledControls;
public EventSuspender()
{
disabledControls = new List<object>();
}
public bool CheckIfDisabled(object sender)
{
if (disabledControls.Contains(sender))
{
disabledControls.Remove(sender);
return true;
}
else
{
return false;
}
}
public void SetTextValue(TextBox box, string value)
{
if (box.Text != value)
{
disabledControls.Add(box);
box.Text = value;
}
}
public void SetNumericValue(NumericUpDown num, decimal value)
{
if (num.Value != value)
{
disabledControls.Add(num);
if (value > num.Maximum) num.Value = num.Maximum;
else if (value < num.Minimum) num.Value = num.Minimum;
else num.Value = value;
}
}
public void SetCheckBox(CheckBox box, bool value)
{
if (box.Checked != value)
{
disabledControls.Add(box);
box.Checked = value;
}
}
public void SetRadioButton(RadioButton button, bool value)
{
if (button.Checked != value)
{
if (value)
{
disabledControls.Add(button);
}
button.Checked = value;
}
}
}
// one-liner in event handlers:
// if (suspender.CheckIfDisabled(sender)) return;
How to handle a control event (Windows Forms .NET)
Use the Properties pane to remove the handler of an event: Open the Visual
Designer of the form containing the control to change. Select the control.
Change the Properties pane mode to Events by pressing the events button ().
Find the event containing the handler you want to remove, for example, the
Click event: Right-click on the event and choose Reset.
private void button1_Click(object sender, EventArgs e)
{
// Create and add the button
Button myNewButton = new()
{
Location = new Point(10, 10),
Size = new Size(120, 25),
Text = "Do work"
};
// Handle the Click event for the new button
myNewButton.Click += MyNewButton_Click;
this.Controls.Add(myNewButton);
// Remove this button handler so the user cannot do this twice
button1.Click -= button1_Click;
}
private void MyNewButton_Click(object sender, EventArgs e)
{
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Create and add the button
Dim myNewButton As New Button() With {.Location = New Point(10, 10),
.Size = New Size(120, 25),
.Text = "Do work"}
'Handle the Click event for the new button
AddHandler myNewButton.Click, AddressOf MyNewButton_Click
Me.Controls.Add(myNewButton)
'Remove this button handler so the user cannot do this twice
RemoveHandler Button1.Click, AddressOf Button1_Click
End Sub
Private Sub MyNewButton_Click(sender As Object, e As EventArgs)
End Sub
button1.Click -= button1_Click;
RemoveHandler Button1.Click, AddressOf Button1_Click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
'Do some work to handle the events
End Sub
C# windows forms cancel event
c# windows forms cancel event. private void form1_FormClosing (object sender,
FormClosingEventArgs e) { MessageBox.Show («Form Closing»); e.Cancel = true;
MessageBox.Show («Form Closing Canceled.»); }
private void form1_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Form Closing...");
e.Cancel = true;
MessageBox.Show("Form Closing Canceled.");
}
Sometimes, Developers don’t want Users to close or leave a Form right away as Application still has some back ground process going on or it requires a confirmation before closing. In C# Windows Application, you can code at FormClosing Event. Have a look at this code snippet.
private void MailUI_FormClosing(object sender, FormClosingEventArgs e)
{
if (backgroundWorkerMailOne.IsBusy)
{
MessageBox.Show("Mail has not been sent yet");
e.Cancel = true;
}
}
This will generate a Message if the Background Worker is busy. You may even ask for confirmation at this Event.
// this will restrict user from closing the Form
e.Cancel = true;
// this one will allow user to close the Form
e.Cancel = false;
Thanks
A Rahim Khan
- 2010
- 08/11
- CATEGORY
- C#
- TAGS
- C#
Form Close Event
Form Closing
Создание непрямоугольных форм. Закрытие формы
Последнее обновление: 31.10.2015
По умолчанию все формы в Windows Forms являются прямоугольными. Однако мы можем создавать и непрямоугольные произвольные формы.
Для этого используется свойство Region. В качестве значения оно принимает объект одноименного класса Region.
При создании непрямоугольных форм, как правило, не используются границы формы, так как границы задаются этим объектом
Region. Чтобы убрать границы формы, надо присвоить у формы свойству FormBorderStyle
значение None
.
И еще один аспект, который надо учитывать, заключается в перемещении, закрытии, максимизации и минимизации форм. То есть в данном случае ,
как в обычной форме, мы не сможем нажать на крестик, чтобы закрыть форму, не сможем ее переместить на новое место. Поэтому нам надо
дополнительно определять для этого программную логику.
Итак, перейдем к коду формы и изменим его следующим образом:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HelloApp { public partial class Form1 : Form { Point moveStart; // точка для перемещения public Form1() { InitializeComponent(); this.FormBorderStyle = FormBorderStyle.None; this.BackColor = Color.Yellow; Button button1 = new Button { Location = new Point { X = this.Width / 3, Y = this.Height / 3 } }; button1.Text = "Закрыть"; button1.Click += button1_Click; this.Controls.Add(button1); // добавляем кнопку на форму this.Load += Form1_Load; this.MouseDown += Form1_MouseDown; this.MouseMove += Form1_MouseMove; } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void Form1_Load(object sender, EventArgs e) { System.Drawing.Drawing2D.GraphicsPath myPath = new System.Drawing.Drawing2D.GraphicsPath(); // создаем эллипс с высотой и шириной формы myPath.AddEllipse(0, 0, this.Width, this.Height); // создаем с помощью элипса ту область формы, которую мы хотим видеть Region myRegion = new Region(myPath); // устанавливаем видимую область this.Region = myRegion; } private void Form1_MouseDown(object sender, MouseEventArgs e) { // если нажата левая кнопка мыши if (e.Button == MouseButtons.Left) { moveStart = new Point(e.X, e.Y); } } private void Form1_MouseMove(object sender, MouseEventArgs e) { // если нажата левая кнопка мыши if ((e.Button & MouseButtons.Left) != 0) { // получаем новую точку положения формы Point deltaPos = new Point(e.X - moveStart.X, e.Y - moveStart.Y); // устанавливаем положение формы this.Location = new Point(this.Location.X + deltaPos.X, this.Location.Y + deltaPos.Y); } } } }
Создание области формы происходит в обработчике события Form1_Load. Для создания области используется графический путь — объект класса
System.Drawing.Drawing2D.GraphicsPath
, в который добавляется эллипс. Графический путь позволяет создать фигуру любой формы,
поэтому, если мы захотим форму в виде морской звезды, то нам просто надо должным образом настроить используемый графический путь.
Для закрытия формы в обработчике события нажатия кнопки button1_Click
форма закрывается программным образом: this.Close()
Для перемещения формы обрабатываются два события формы — событие нажатия кнопки мыши и событие перемещения указателя мыши.