Child form closed on enter click - c#

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.

Related

I'm trying to call a method from a textbox in winforms when the enter key is pressed and it's not working

The if statement is being checked until I hit enter then it goes straight to another method. My guess is there is something else on the form that is getting triggered when I hit enter but I can't find it despite my search.
I want to not have to put a button on the form to call this function, the button I had worked but I just want to be able to hit enter from my textbox input.
Here is my code below:
private void textBox1firstName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
searchAD();
}
}
private void textBox2lastName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
searchAD();
}
}
searchAD() is not getting called despite hitting enter. Any suggestions? Thank you!
The form has a KeyDown event, but also has a "AcceptButton" property, which hooks the [Enter] keypress and can call an event handler. Check if there are event-handlers attached to either of those on the form.

Passing arguments to a Button click event function

I have a Form that consists of a Username textbox, a Password textbox and a Login button.
I want to activate the Login button after pressing enter once the password textbox is filled. I do not know how to call the function.
private void Login_button_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(IntrarePassword.Text) || string.IsNullOrEmpty(IntrareUser.Text))
return;
Form2 form2 = new Form2();
form2.Username = IntrareUser.Text;
form2.Show();
}
private void IntrarePassword_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
Login_button_Click();
}
What should be the Login_button_Click parameters be?
The easiest solution would be to register on the KeyPress event of the password control, filter the key pressed then update the Enabled property of the button.
Msdn is your friend ^^ : https://learn.microsoft.com/en-us/dotnet/framework/winforms/how-to-handle-keyboard-input-at-the-form-level
EDIT: Misunderstood your question, my bad.
As you don't use the arguments, can pass null/default or extract your code into a new parameterless method that both event handler can call.
Set the form's AcceptButton as Login_button and it will get clicked on pressing enter key.
Enter this code in the form's Load event:
this.AcceptButton = Login_button;
If you want the Login button to get enabled after pressing enter key, here's it:
In your form, set Login_button's Enabled property to false from Properties tab.
Change your code to:
private void Login_button_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(IntrarePassword.Text) || string.IsNullOrEmpty(IntrareUser.Text))
return;
Form2 form2 = new Form2();
form2.Username = IntrareUser.Text;
form2.Show();
}
private void IntrarePassword_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
Login_button.Enabled = true;
}

why this.close() close application

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().

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.

Not able to capture Enter key in WinForms text box

When the user is entering a number into a text box, I would like them to be able to press Enter and simulate pressing an Update button elsewhere on the form. I have looked this up several places online, and this seems to be the code I want, but it's not working. When data has been put in the text box and Enter is pressed, all I get is a ding. What am I doing wrong? (Visual Studio 2008)
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnMod.PerformClick();
}
}
Are you sure the click on the button isn't performed ? I just did a test, it works fine for me. And here's the way to prevent the "ding" sound :
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnMod.PerformClick();
e.SuppressKeyPress = true;
}
}
A few thoughts:
does the form have an accept-button (set on the Form) that might be stealing ret
does the textbox have validation enabled and it failing? try turning that off
does something have key-preview enabled?
Under "Properties" of the Form. Category (Misc) has the following options:
AcceptButton, CancelButton, KeyPreview, & ToolTip.
Setting the AcceptButton to the button you want to have clicked when you press the Enter key should do the trick.
Set e.Handled to true immediately after the line btnMod.PerformClick();.
Hope this helps.
I had to combine Thomas' answer and Marc's. I did have an AcceptButton set on the form so I had to do all of this:
private void tbxMod_Enter(object sender, EventArgs e)
{
AcceptButton = null;
}
private void tbxMod_Leave(object sender, EventArgs e)
{
AcceptButton = buttonOK;
}
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Click your button here or whatever
e.Handled = true;
}
}
I used t0mm13b's e.Handled, though Thomas' e.SuppressKeyPress seems to work as well. I'm not sure what the difference might be.
form properties > set KeyPreview to true
The simple code below works just fine (hitting the Enter key while in textBoxPlatypusNumber displays "UpdatePlatypusGrid() entered"); the form's KeyPreview is set to false:
private void textBoxPlatypusNumber_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter)
{
UpdatePlatypusGrid();
}
}
private void UpdatePlatypusGrid()
{
MessageBox.Show("UpdatePlatypusGrid() entered");
}

Categories