why this.close() close application - c#

I have a window in wpf that i want on the escape button to close the window. So i wrotethis code on PreviewKeyDown event, but it closes the entire application, including the main window and current window. I just want to close current window.
//this code for open second window
private void M_Mahale_Click(object sender, RoutedEventArgs e)
{
Tanzimat.MahaleWin Mahale = new Tanzimat.MahaleWin();
Mahale.ShowDialog();
}
//this code for PreviewKeyDown event on second window and current window
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
this.Close();
}
}

OK, based on this comment //this code for PreviewKeyDown event on second window and current window you have the same code in both windows in the PreviewKeyDown -so in both windows change the code to this:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
e.Handled = true;
this.Close();
}
}
and that will keep other windows from getting the event when it's been handled already. See, what's happening is when the escape key is pressed both windows are getting the message, and you didn't tell the main window (i.e. the one behind the current one) not to process it.

You window has a name Mahale and or order to close it from the main window, you should call:
Mahale.Close();
If you call this.Close(); in main form it is quite natural for the program to exit

You can use this.Hide() to hide that window, but that window still exists.

I think the best way to achieve your goal is using of Button's IsCancel property.
You can set the IsCancel property on the Cancel button to true,
causing the Cancel button to automatically close the dialog without
handling the Click event.
See here for examples.

do :
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
this.Hide();
}
}
instead.
Close() close every frames. Use hide().

Related

Child form closed on enter click

I have two Forms Frm1 and Frm2.
Both having single textbox.
On keyup event of first form textbox, second form is opened if KeyChar is ENTER.
Now on KeyUp event for textbox in 2nd form I am closing this form i.e submitting.
Now both events are called. Is there any way to get rid of thi?
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Frm2 frm=new Frm2();
Frm2.RefToForm1=this;
frm.StartPosition = FormStartPosition.CenterParent;
frm.ShowDialog(this);
}
}
Now in second form
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.RefToForm1.textBox1.Text=textBox2.Text;
this.Close()
}
}
Problem is when I press enter on textBox1 , form2 is opened and closed immediately.
Any Solutions
you can set the windows form property for-
1- AcceptButton - button id ( on which button you have to submit.)
2-CancelButton - button id ( on which button you have to close the form.)
There's no reason that releasing the Enter key when textBox1 is focused and no instance of Frm2 is opened yet, would also raise the KeyUp event on textBox2 in Frm2.
Are you sure you don't have some addition code in your project that's causing this behavior? Did you try putting a breakpoint on this.Close() in textBox2_GotFocus method to see if it actually gets executed in your scenario?
I even created a small sample project using your code with some minor modifications to make it work (explained in comments):
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Frm2 frm=new Frm2();
frm.RefToForm1=this; // you said RefToForm1 isn't static and it shouldn't be
frm.StartPosition = FormStartPosition.CenterParent;
frm.ShowDialog(this);
}
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.RefToForm1.textBox1.Text=textBox2.Text;
this.Close(); // missing semicolon
}
}
public Form1 RefToForm1 { get; set; } // property in Frm2
You can download this working sample project from here.
define a boolean variable in form 2, set it to false initially and close the form based on that variable. You could set it to true later when you need it. You could use the GotFocus method of the textbox to set to it true. e.g
textBox2.GotFocus += textBox2_GotFocus;
Set the boolean to true inside the textBox2_GotFocus method. Your key_up method would look like this :
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if(boolean_var){
this.RefToForm1.textBox1.Text=textBox2.Text;
this.Close();
}
}
}
Perhaps you could prevent the second form from closing if the textbox is empty -- assuming something needs to go in there for it to close.
Could you give us more information about what you're trying to do with this? Perhaps there's another way to solve the feature you're trying to create.

How can I make Ctrl+M an event that brings up a form?

I have this code:
private void button5_Click(object sender, EventArgs e)
{
Magnifier20070401.MagnifierForm mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
It shows the target form correctly. But instead of using a button click, I want to use Ctrl+M to show this form. If the users types Ctrl+M again, I want to close the the form.
How can I do this?
Edit:
This is what i did wich is working :
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "M")
{
Magnifier20070401.MagnifierForm mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
}
In the constructor of Form1 i added:
this.KeyPreview = true;
So now when i click on Ctrl+M i see the new Form.
What i need now is how to make that if i click again on Ctrl+M it will close the new Form.
Maybe using a flag ?
Edit:
This is what i did now:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "M")
{
if (mf == null)
{
mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
else
{
mf.Close();
this.Invalidate();
}
}
}
But even doing this.Invalidate(); i don't see the new Form closed.
But if im using put a breakpoint on the mf.Close(); and step into(F11) i see it close when making continue.
Why it dosen't close without using a breakpoint ?
You can add onKeyPress or onKeyDown
and check if Ctrl+M were pressed
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
if (((Control.ModifierKeys & Keys.Control) == Keys.Control)
&& (e.KeyChar == 'M'|| e.KeyChar == 'm'))
{
mf.Show();
}
You would use the InputBindings object. I think in your case, probably best to put that at the Window level (Window.InputBindings). More information here:
http://msdn.microsoft.com/en-us/library/system.windows.input.inputbinding.aspx
You can solve this in 2 ways.
If you are using a GUI interface, add a MenuItem control on your Menu, and put the Shortcut property to Ctrl+M then double click the MenuItem to edit the code, then call your launchMagnifier() function. If you do NOT want your menu to show, just set the visible properties to false. This keeps the menu hidden if you do not want it, yet still holds the functionality.
If you do not want the MenuItem, you can catch keys that are pressed in your form. So in your frmMain.cs form, add an event to capture keys, then when Ctrl+M is pressed, invoke launchMagnifier()
A few ways to do that.
On your form set the KeyPreview Property to true
Then add an OnKeyPress or OnKeyDown event handler to the form.
In that test for Ctrl-M and show / destroy the form and set handled (e.Handled) to true.
Any other keypress will be passed on to the currently focused control as it hasn't been handled.

Troubles with onFormClosing in c#

I'm trying to implement some code that asks if the user wants to exit the application I've made.
It's in c# and is a windows form application.
I've had very little sleep this week and can't seem to get my head around the onFormClosing event. Could some please give me the exact code I should use to have code executed when the user clicks on the close button (the 'x' in the top right).
Please find it in your heart to help a sleep deprived moron.
Double-click the form's FormClosed event in the events tab of the Properties window in the designer.
The FormClosing event allows you to prevent the form from closing by setting e.Cancel = true.
Well, the event is called FormClosing and is cancellable. Subscribe to it, do your stuff and let the user close their form. This event is fired if the "x" button is used or if you close the form yourself.
You can subscribe to it in the designer by highlighting the form and looking in the events tab of the properties window, as SLaks says, then double-click it. You don't need to do anything special to cope with the "x" button.
The easiest way is to activate the form in the designer and find the event FormClosing in the properties windows and then just double click the event.
Then just do the following:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
var result = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo);
if (result != System.Windows.Forms.DialogResult.Yes)
{
e.Cancel = true;
}
}
}
If you do not specify that the reason has to be UserClosing, it will stop windows from shutting down if you do not exit the program first which is not a good practice.
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you sure that you wan't to close this app", "Question", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
e.Cancel = true;
}
I hope this helps
You can add event handler manually. Example to add event handler in constructor:
public frmMain()
{
InitializeComponent();
FormClosing += frmMain_FormClosing;
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
//your code
}
Make derive your form fromf the System.Windows.Forms.Form and put this override:
protected override void OnFormClosing(CancelEventArgs e)
{
if (bWrongClose)
{
bWrongClose = false;
e.Cancel = true; // this blocks the `Form` from closing
}
base.OnFormClosing(e);
}

Visual C#: Exit the Program Check

In Visual C#, how can I detect if the user clicks the X button to close the program? I want to ask the user if they'd like to perform a certain action before exiting. I have an exit button in my program itself, and I know I can code it as follows:
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result;
if (logfiletextbox.Text != "")
{
result = MessageBox.Show("Would you like to save the current logfile?", "Save?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result == DialogResult.Yes)
{
savelog.PerformClick();
}
}
Environment.Exit(0); //exit program
}
But how can I do this for the X button that is already built into the program?
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("cancel?", "a good question", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = true;
}
}
It's the "FormClosing" - event of the form. Have fun, friend.
Add an event handler for FormClosing on the form.
The Form designer will do this for you automatically if you select the event, but to do it manually:
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);
And then add the handler into your code:
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
//Code here
}
If you don't want to close the form then you can set:
e.Cancel = true;
There is a FormClosing event you can bind to that gets fired when the form is about to close. The event handler includes a link to the reason the form is closing (user action, OS shutdown, etc), and offers you an option to cancel it.
Check out the MSDN article here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx
use the Application.Exit or Form.Closing event. Exit won't let you cancel, so Closing is probably a better choice
Just use FormClosing event of form
If you're using a form, you can catch the Form.FormClosing event.
It can be cancelled by setting the Cancel property in the args, based on user input.

Closing a form and doing something on return to another form

I have a mainForm and a saveForm.
I never close the mainForm, just let the saveForm appear over the top.
When i close the saveForm, I want a piece of code to run on returning to mainForm.
What is the best way to achieve this?
In addition to #benPearce's answer, if you are content to have saveForm appear modally, then you can just call:
So in the mainForm, I am assuming you have a Save button (let's call it btnSave) of some kind that brings up saveForm, right? Right. So double click on that Save button and Visual Studio will create an event handler for you. Type in the code below.
private void btnSave_Click(object sender, EventArgs e)
{
saveForm sf = new SaveForm();
if (sf.ShowDialog() == DialogResult.OK)
{
// do your thing
}
}
Of course, you have to make sure that the saveForm is setting the DialogResult. For instance, assuming you have an OK button in the saveForm that is supposed to close the saveForm... In the Click event for the OK button you would do this:
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
In mainForm, subscribe to the FormClosed event on the saveForm, put your code in the event handler for this event
void saveForm_FormClosed(object sender, FormClosedEventArgs e)
{
/// code here
}

Categories