I have two forms, Form1 and Form2. Form2 is opened from a button located in Form1. All I want is that when I close Form2 from X(cross) button in the upper right corner of the window, the focus is set to textbox1 of a Form1. Any help regarding this ??
Try this
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
f.FormClosed += f_FormClosed;
}
void f_FormClosed(object sender, FormClosedEventArgs e)
{
textBox1.Focus();
}
Write this code in form1
button click
event:
form2 fm2 = new form2();
fm2.ShowDialog(); //to show as child form of Form1
textbox.Focus(); //as Form2 closes it will focus to your textbox now
You can assign an event handler to form2
's Close
event manually like this:
form2 = new Form2();
form2.Closed += Form2Closed;
form2.Show();
public void Form2Closed(object sender, FormClosedEventArgs e)
{
textBox2.Focus();
}
Please note that this works in your case, as you're not showing form2
with ShowDialog
!
Also, this sets the focus if the form is closed by some other way, too, for example a button on the form. If you really only want to focus the text box if the close box of the window is clicked, you need to do a bit more.
public void Form2Closed(object sender, FormClosedEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
Form2 f2 = sender as Form2;
if (!f2.ClosedByUserElement)
textBox2.Focus();
}
}
Also, in Form2
you need a property ClosedByUserElement
which is normally false
, but set to true
whenever the user closes the form by other means than the red X
, for example a button:
private void button1_Click(object sender, EventArgs e)
{
ClosedByUserElement = true;
Close();
}
That way you can decide whether the user closed the window using the window's close box ( ClosedByUserElement
would be false
) or by a manual call to Close
, for example when a button is clicked ( ClosedByUserElement
would be true
).
如果Form2
是一个用ShowDialog()
方法打开的模态表单,你可以简单地在Form1按钮Click事件中添加这个代码,在表单打开之后: this.textbox1.Focus();
Write this Code in Form1's Button Click Event by which button you open the Second Form
Form2 frm2 = new Form2();
frm2.ShowDialog(); // do what you want in your form, then close it
yourTextbox.Focus();
yourTextbox.BackColor = Color.LightYellow; // instead of LightYellow Write whatever colour you want
Hope this Helps You ....
如果直接从一个父表单打开,则可以使用其他表单加载事件,如果要更改聚焦文本框,则可以使用父表单的用例。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.