Preventing Windows from shutting down - c#

I am using windows form,I want to display the message to the user that the process is not complete if the user tries to shut down the windows or tries to closes the application before completion of process(the user forgot to complete the process),if the user presses OK i want to stop the window from shutting down and let the user complete the process,I did find some code on the net to do so but it is in VB not in c#
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
{
Microsoft.VisualBasic.Interaction.Shell("shutdown -a", AppWinStyle.MinimizedFocus, false, -1);
MessageBox.Show("Shutdown process cancelled!");
}
}

Better to use this piece of code snippet instead, play with e.Cancel as per your requirement:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
{
if (MessageBox.Show("You are closing this app.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)
return;
else
e.Cancel = true;
}
}
Reference: SystemEvents.SessionEnding Event
Occurs when the user is trying to log off or shut down the system.

Related

When does 'e.Cancel = true' in FormClosing NOT prevent logoff?

I have a Winforms app that minimizes to the Taskbar when a user clicks on the X. It does not prevent a user from logging off.
On the other hand, I have an app that shows a dialog when a user clicks the X, and it does prevent logging off showing:
"This app is preventing you from signing out."
I've tried tracking down what exactly is the difference between them but haven't found the difference. I thought it would be the dialog, but a test app has shown that in any case that the app sets e.Cancel = true; in FormClosing - the test app prevents logoff. This doesn't matter if the app shows a dialog or not, and if ShowInTaskbar is true or false. And both apps and the test app only Cancel if e.CloseReason == CloseReason.UserClosing.
So basically what I'm asking is when does e.Cancel = true not prevent logging off?
This doesn't matter if the app shows a dialog or not... And both apps and the test app only Cancel if e.CloseReason == CloseReason.UserClosing
That's the whole point, it doesn't matter whether you show a dialog or not. In the first app, you're not calling e.Cancel == true; at all because e.CloseReason is not UserClosing, it is WindowsShutDown.
According to the documentation:
UserClosing
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.
You can confirm that it is in fact WindowsShutDown, by running some simple test like the following:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.IO.File.WriteAllText(#"D:\SomePath\CloseReason.txt", e.CloseReason.ToString());
if (e.CloseReason == CloseReason.UserClosing) e.Cancel = true;
}
If you want to prevent the shutdown/log-off, you can either set e.Cancel to true without a condition, or by checking if e.CloseReason == CloseReason.WindowsShutDown:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// e.Cancel = true;
// Or..
if (e.CloseReason == CloseReason.UserClosing ||
e.CloseReason == CloseReason.WindowsShutDown)
{
e.Cancel = true;
}
}
But, please use this responsibly and be aware that the user can always force the shutdown/log-off as explained in this answer.
Edit:
If, on the other hand, you have some logic which might prevent the form from closing (i.e., by calling e.Cancel = true;) and you don't want that logic to apply when shutting down (or logging off), I always use something like the following:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown) return; // Go ahead and close.
if (!SafeToClose())
{
// Optional:
if (MessageBox.Show("Important process is running. Stay?",...) == DialogResult.Yes)
{
e.Cancel = true;
}
// Or directly:
//e.Cancel = true;
}
}

How can I stop running application in backgournd and exit without exception?

I Have many winforms in a project. When I click on Cross button to close one specific form maybe it is running in the background process. So How can I stop that from running in background when I click on cross button. I have the code for exiting application;
Application.Exit();
But this also shows exception when from frmMainMenu I click on logoutMenuStrip option. For the LogoutMenuStrip I have the following code to forcefully exit the application. But still it shows some exception. My Question is how can I Prevent all exception when I click on that logoutMenuStrip.
I supposed that maybe on clicking the other forms closing they get
running in background
Code for LogoutMenuStrip:
private void logoutToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show("Are you sure to QUIT ?", "Exit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
Application.Exit();
}
catch
{
Application.Exit();
}
}
Thanks in advance :)
If you have multiple instances of your application running and one or more of those is in background, you can enumerate the processes and then kill them.
var processes=Process.GetProcessByName( "AppName" );
foreach(var process in processes )
process.Kill();
use Environment.Exit(0); it closes everything and shuts down your application
private void logoutToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show("Are you sure to QUIT ?", "Exit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
Environment.Exit(0);
}
catch
{
Environment.Exit(0);
}
}

Ask confirmation message only once from user in C# Window Appliaction

i built an windows application using c# .
On form closing event i wrote a code like this to ask confirmation form user...
private void Approve_User_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Do you really want to QUIT application...?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Application.Exit();
}
else
{
e.Cancel = true;
}
}
sometimes it ask four times , even upto five times....
I want this only once if user press Yes then application should exit.
I need your help and suggestions.
Thanks in advance.
Apparently you are subscribing to this Approve_User_FormClosing event in a place which execute a few times. If you subscribe 4,5 times it will execute 4,5 times.
If you just want to capture application exit event have a look at this thread.
Edit
You need something like below to achieve your weird requirement.
private bool isExiting = false;
private void Approve_User_FormClosing(object sender, FormClosingEventArgs e)
{
if (isExiting)
return;
if (MessageBox.Show("Do you really want to QUIT application...?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
isExiting = true;
Application.Exit();
}
else
{
e.Cancel = true;
}
}

How do i close shut down my application from another Form?

I have this event in a new Form:
private void CrawlLocaly_FormClosed(object sender, FormClosedEventArgs e)
{
}
Im not sure if to use Closed or Closing.
The reason is that i want to check if the user shut down the program for example by just closing the application from the taskbar.
If he did close it from the taskbar mouse right click then close then i want it to close all the program and not only this Form.
How can i do it ?
Application.Exit();
Will shut down your application.
Im not really sure if you can detect if he closed it via rightmouse menu. As far as I know you can only see the reasons provided in the FormClosedEventArgs. FormClosing will provide you with same reasons.
Use this event:
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
{
//close forms
Application.Exit();
}
}
There is no way to check whether user closed your form by clicking 'X' or through TaskBar or any other way as the result of CloseReason will always be CloseReason.UserClosing
Well I Stick with such issue also.
In mine app I have 2 forms, #1 main, #2 - for settings - if user close it i want to know save settings or not. Also if settings are null - close app not only form, if user click button save - I want to close (hide) #2 form.
So where is my solution we set tag value to 1 if click button save, so we will know "who" try to close form:
Predefined:
btnSave.Tag = 0;
On save button click event:
btnSave.Tag = 1;
this.Hide();
its will trigger onclose event:
private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
if (btnSave.Tag.ToString() == "0")
{
DialogResult dlg = MessageBox.Show("Do you want to exit without finished setup connection?", "Form", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlg == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
this.Dispose();
Application.Exit();
}
}
else
{
this.Hide();
}
}

Ask the user before closing C# WPF application

I want to ask the user before closing the application.
I'm using C# .NET 4.0 WPF. I can do it in windows forms, but not in WPF.
Event is fired when the user want to close the app. Message box appears, bun no matter which button is pressed (Yes or No) the application always closes. Why? Where is the mistake?
It works, but only when the user presses the "X". When the user presses the close button with Application.Current.Shutdown(); it is not working.
private void MainWindowDialog_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Do you really want to do that?",
"Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No)
{
e.Cancel = true;
}
}
The Closing event cannot be cancelled if you call Application.Current.Shutdown(). Just call the Window.Close() method instead, which will give you a chance to veto the close operation. Once all your program's windows have closed the application will shutdown automatically.
For more information checkout the Application Management page on MSDN.
Just call YourMainWindow.Close() and use the Closing event as described before.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
e.Cancel = false;
else
e.Cancel = true;
}
Why don't you just ask the user whether he wants to close the application, and then call Application.Current.Shutdown() like this:
private void closeButton_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to exit?", "Confirm",
MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
}
}

Categories