How to prevent or block closing a WinForms window?
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
var window = MessageBox.Show(
"Close the window?",
"Are you sure?",
MessageBoxButtons.YesNo);
e.Cancel = (window == DialogResult.No);
}
How to cancel closing winform?
The FormClosing
(as opposed to your FormClosed
) event's FormClosingEventArgs
contains a Cancel
boolean that you can change to true. Note that this will occur even if you close the form programmatically.
this.FormClosing += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
e.Cancel = true;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
To determine how the form was closed, it also includes a CloseReason
.
See docs here and here.
How to prevent Closing and Disposing of a winform in the FormClosing event?
e.Cancel = true
prevents the window from closing - it stops the close event.
e.Cancel = false
allows the "close event" to continue (resulting in the window closing and being disposed; assuming nothing else stops it).
It seems you want to do this:
method PPMain.PPMain_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
begin
e.Cancel := true;
if MessageBox.Show('Are you sure you want to close the window?','PPMain',MessageBoxButtons.YesNo) = DialogResult.Yes then
begin
Hide;
end
end
e.Cancel := true;
prevents the window from closing. The user is then prompted, if they say yes Hide;
hides the window (without disposing). If the user clicks No, nothing happens.
It might be a good idea to detect what kind of close action is being performed. Using e.CloseReason
so as not to prevent closing during OS shutdown or something along those lines.
Like this:
method PPMain.PPMain_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
begin
if e.CloseReason = System.Windows.Forms.CloseReason.UserClosing then
begin
e.Cancel := true;
if MessageBox.Show('Are you sure you want to close the window?','PPMain',MessageBoxButtons.YesNo) = DialogResult.Yes then
begin
Hide;
end
end
end
How do prevent any Form from closing using alt + F4
Handle Atl+F4
by your self and set it handled.
In the form constructor first set
this.KeyPreview = true;
Then handle the keyDown event
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.F4)
{
e.Handled = true;
}
}
How to restrict user from closing the Winform c#
You could also not show the close button:
http://blogs.msdn.com/b/atosah/archive/2007/05/18/disable-close-x-button-in-winforms-using-c.aspx
Cody Gray provided a better link in the comments that also disallows the Alt-F4 close:
https://stackoverflow.com/a/4655948/366904
Can I disable the 'close' button of a form using C#?
You handle the Closing event (and not the Closed event) of the Form.
And then you use e.CloseReason to decide if you really want to block it (UserClose) or not (TaskManager Close).
Also, there is small example Disabling Close Button on Forms on codeproject.
How do I prevent the app from terminating when I close the startup form?
The auto-generated code in Program.cs was written to terminate the application when the startup window is closed. You'll need to tweak it so it only terminates when there are no more windows left. Like this:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var main = new Form1();
main.FormClosed += new FormClosedEventHandler(FormClosed);
main.Show();
Application.Run();
}
static void FormClosed(object sender, FormClosedEventArgs e) {
((Form)sender).FormClosed -= FormClosed;
if (Application.OpenForms.Count == 0) Application.ExitThread();
else Application.OpenForms[0].FormClosed += FormClosed;
}
Disabling Minimize & Maximize On WinForm?
The Form
has two properties called MinimizeBox
and MaximizeBox
, set both of them to false
.
To stop the form closing, handle the FormClosing
event, and set e.Cancel = true;
in there and after that, set WindowState = FormWindowState.Minimized;
, to minimize the form.
Forms closing without pop ups(blocking popup and forcefully closing other forms) on main form exit
You'll need to pay attention to the e.CloseReason property value that's passed to you in the FormClosing event. Only prompt the user if e.CloseReason == CloseReason.UserClosing. This also ensures that you don't display the dialog when the user shuts down Windows. For example:
private void Form2_FormClosing(object sender, FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing && !saved) {
switch (MessageBox.Show(this, "Save changes?", "Closing",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) {
case DialogResult.Yes: Save(); break;
case DialogResult.No: break;
case DialogResult.Cancel: e.Cancel = true;
}
}
}
Do consider always saving changes so the user won't suffer from unexpected data loss. Say to a temporary file that you re-open when the program starts back up.
How to Disable Alt + F4 closing form?
This does the job:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form_closing event before closing the form:
this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Close();
Related Topics
How to Access Resourcedictionary in Wpf from C# Code
How to Compare Two Objects in Unit Test
How to Detect Iis Version Using C#
Regex to Get Src Value from an Img Tag
When Should I Use Out Parameters
C# Invalid Attempt to Call Read When Reader Is Closed
How to Stop an Application from Opening
ASP.NET Core Disable Authentication in Development Environment
Deserialize JSON to Anonymous Object
Multiple SQL Statements in One Roundtrip Using Dapper.Net
How to Write Out a Text File in C# with a Code Page Other Than Utf-8
Getters and Setters Are Bad Oo Design
How to Share Sessions Between PHP and ASP.NET Application