c# shutdown application through exit menu and closing event - c#

I want to close my application from Menu having Exit option and through Window closing And for both I have added prompt message.
But If I called exit then gives prompt message two times because on Exit_Click event after System.Windows.Application.Current.Shutdown(); it goes to ShellWindow_Closing
public partial class SWindow : Window
{
public SWindow()
{
this.Closing += ShellWindow_Closing;
}
private void ShellWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Any running migration task will be aborted. \nAre you sure you want to exit the application ?",
"Exit Proventeq Migration Acclerator",
MessageBoxButton.YesNo,
MessageBoxImage.Question) == MessageBoxResult.No)
e.Cancel = true;
}
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Any running migration task will be aborted. \nAre you sure you want to exit the application ?", "Exit Proventeq Migration Acclerator", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
e.Handled = true;
}

Whenever You press Exit button or You close the application by ALT + F4 or the right-up X (cross) will be pressed, it always come to Your app closure.
Simplier way is to handle BtnMenuExit_Click as App closure. Then by other behaviour - event for Window close to cancel based on result of message box.
public partial class SWindow : Window
{
public SWindow()
{
this.Closing += ShellWindow_Closing;
}
private void ShellWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Any running migration task will be aborted.\nAre you sure you want to exit the application ?", "Exit Proventeq Migration Acclerator", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
{
e.Cancel = true;
}
}
private void BtnMenuExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
//designer part
public partial class SWindow
{
//other code
private void InitializeComponent()
{
Button BtnMenuExit = new Button();
BtnMenuExit.Click += new EventHandler(BtnMenuExit_Click);
//other styles etc..
}
//other code
}

Related

Close button is not closing the form properly

My form contains a button named as close. I just put the below code in the close button click... Then the 2nd code set is for the form closing. But if I execute this when I click the close button a MessageBox will appear. When I click the "Yes" button, the form is not closing but if I click the "Yes" button second time the form will be closed. What is the reason? Can you, please, help me?
private void btnClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// MessageBox.Show("The application has been closed successfully.",
// "Application Closed!",
// MessageBoxButtons.OK);
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
-------------------------------------
private void frminventory_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
Do not close/exit Application, but Form:
private void btnClose_Click(object sender, EventArgs e) {
// On btnClose button click all we should do is to Close the form
Close();
}
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
// ...warn him/her and cancel form closing if necessary
e.Cancel = MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) != DialogResult.Yes;
}
}
Edit: Usually we ask direct questions to user (it's unclear what wrong things can arise if I just "Close This Form"), e.g.
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// Data has not been changed, just close without pesky questions
if (!isEdited)
return;
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
var action = MessageBox.Show(
"You've edited the data, do you want to save it?"
Text, // Let user know which form asks her/him
MessageBoxButtons.YesNoCancel);
if (DialogResult.Yes == action)
Save(); // "Yes" - save the data edited and close the form
else if (DialogResult.No == action)
; // "No" - discard the edit and close the form
else
e.Cancel = true; // "Cancel" - do not close the form (keep on editing)
}
}
So, because i can't comment, i would do something like this.
//Create this variable
private bool _saved = true;
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
DoSomething();
_saved = true;
}
//Raised when the text is changed. I just put this for demonstration purpose.
private void textBox1_TextChanged(object sender, EventArgs e)
{
_saved = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_saved == false)
{
var result = MessageBox.Show("Are you sure you want to close?\nYou may have unsaved information", "Information", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
_saved = true;
Application.Exit();
}
else
e.Cancel = true;
}
}
Hope this can solve yor problem

WPF dialogBox Don't close the application

I made a custom dialog box in WPF. I want , when the user clicks X the dialogBox will be opened, if he wants to exit he should click "yes", if not he should click "no".
static public bool? close;
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.Hide();
WindowClose windowClose = new WindowClose();
windowClose.ShowDialog();
close = windowClose.DialogResult;
if (close == true)
{
Application.Current.Shutdown();
}
else
{
//DONT CLOSE THE APPLICATION AND SHOW THE CURRENT WINDOW
}
}
the code of the dialog box:
private void button1_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
Not sure if it works differently in WPF, but in standard winforms in the code for the dialog box you'd set (for example) the DialogResult to DialogResult.OK (yes) and DialogResult.Cancel (no). You wouldn't need to close the form as this is done automatically when you set the DialogResult
Then in the main form you'd have
If (windowClose.ShowDialog() == DialogResult.OK
{
Application.Current.Shutdown();
}
else
{
//DONT CLOSE THE APPLICATION AND SHOW THE CURRENT WINDOW
}

How to make Exit confirmation yes or no on Control Button using C# Window Form

I have a one issue in my window application, there are two form :login and main.
I have created Exit Button on both form and also coded of Exit Confirmation.
It works fine when we Press Exit Button message No on form 1. But We login to on form to
another form and second form Exit Button message button press No , and then back to return
form one and then click exit btton No ::::::it will display two times message PopUp of confirmation...............
Code
private void Btn_Exit_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Do you want to exit.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
Application.ExitThread();
} else
{ }
}
Plz there is any solution in c#............
Just code this.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Do you want to close this application?", "Exit", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
{
e.Cancel = true;
}
}
In your case consider LoginForm and MainForm , Once you logged in you try to hide the LoginForm and show MainForm. Problem is when you try to close MainForm it will invoke the respective FormCloseEvent and once you chose to close, it automatically invoke parent form that is hiding in background, so it invokes LoginForm's FormCloseEvent. This is the reason for two time Popups.
To resolve this you need to trigger an event i.e whenever Child form is closed you need to raise a flag, so in your parent's FormCloseEvent you need to check for flag, if flag is true you no need to show the pop up.
private bool isMainFormClosed = false;
private void showMainForm()
{
// Hide the loginform UI.
this.Hide();
var mainForm = new MainForm();
// Creating close event for mainform, whenever close icon is clicked it will close the login form which is hiding in background.
mainForm.FormClosed += new FormClosedEventHandler(mainFormClosed);
// Show the mainform UI
mainForm.Show();
}
private void mainFormClosed(object sender, FormClosedEventArgs e)
{
this.isMainFormClosed = true;
this.Close();
}
private void loginFormClosing(object sender, FormClosingEventArgs e)
{
if(!this.isMainFormClosed)
{
DialogResult dialogResult = MessageBox.Show("Do you want to close the application",AppConstants.APPLICATION_NAME,
MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if(dialogResult == DialogResult.No)
e.Cancel = true;
}
}
DialogResult is returned by dialogs after dismissal. It indicates which button was clicked on the dialog by the user.
Code
private void btnExit_Click(object sender, EventArgs e)
{
const string message = "Do you want to exit?";
const string caption = "EXIT";
var result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Application.Exit();
}
else if (result == DialogResult.Yes)
{
this.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Do you want to close this application?", "Exit", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
{
e.Cancel = true;
}
}

How to prevent or block closing a WinForms window?

How can I prevent window closing by showing a MessageBox? (Technology:WinForms with C#)
When the close event occurs I want the following code to be run:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
//close addFile form
} else {
//ignore closing event
}
}
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);
}
Catch FormClosing event and set e.Cancel = true
private void AdminFrame_FormClosing(object sender, FormClosingEventArgs e)
{
var res = MessageBox.Show(this, "You really want to quit?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (res != DialogResult.Yes)
{
e.Cancel = true;
return;
}
}
A special twist might be to always prevent just the user closing the form:
private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = (e.CloseReason == CloseReason.UserClosing);
// disable user closing the form, but no one else
}
Within your OnFormClosing event you can show the dialog and if answer is false (to not show) then set the Cancel property of the EventArgs to true.
For prevent or block the form closing in particular situation you can use this strategy:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (FLAG_CONDITION == true)
{
MessageBox.Show("To exit save the change!!");
e.Cancel = true;
}
}
Straight from MSDN:
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...
}
}
}
In your case you don't need to do anything to explicitly close the form. Unless you cancel it it will close automatically, so your code would be:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if (closeMsg == DialogResult.Yes) {
// do nothing
} else {
e.Cancel = true;
}
}
You can run any code you want when closing the form then, hide the form instead of closing it to prevent it from being disposed
yourFormName.FormClosing += (s, e) =>
{
// any code you want
yourFormName.Hide(); // this hides the form
e.Cancel = true; // this cancels the close event, you can put any boolean exprission
};

Form Closing help

How can I call the button1_Click event in the form closing event so I don't have to copy and paste the code from button1_Click?
public void button1_Click(object sender, EventArgs e)
{
//Yes or no message box to exit the application
DialogResult Response;
Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (Response == DialogResult.Yes)
// Exits the application
Application.Exit();
}
public void xGameThemeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string folder = Application.StartupPath;
string theme = (string)xGameThemeComboBox.Items[xGameThemeComboBox.SelectedIndex];
string path = System.IO.Path.Combine(folder, theme + ".jpg");
Image newImage = new Bitmap(path);
if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
{
this.BackgroundImage = newImage;
}
}
private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
// call button1_Click here
}
what you really need to do:
private bool ShowClose()
{
//Yes or no message box to exit the application
DialogResult Response;
Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
return Response == DialogResult.Yes;
}
public void button1_Click(object sender, EventArgs e)
{
Close();
}
private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !ShowClose();
}
better to extract the code in the button1_Click event into a method, then call the method from both events.
Extract the contents of the button method into it's own method and then call the method from both spots.
button1_Click(null, null);
You should not show the MessageBox at all in the button.
You can simply call Application.Exit() in the button, and the FormClosing event can show the confirmation message.
Application.Exit raises the FormClosing event on all open forms:
A FormClosing event is raised for
every form represented by the
OpenForms property. This event can be
canceled by setting the Cancel
property of their FormClosingEventArgs
parameter to true.
If one of more of the handlers cancels
the event, then Exit returns without
further action. Otherwise, a
FormClosed event is raised for every
open form, then all running message
loops and forms are closed.
I would rewrite it like this:
public void button1_Click(object sender, EventArgs e)
{
// Exits the application
Application.Exit();
}
private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Yes or no message box to exit the application
DialogResult Response;
Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (Response == DialogResult.No)
{
// Cancel the close, prevents applications from exiting.
e.Cancel = true;
} else {
Application.Exit();
}
}

Categories