Focus textbox on main form after closing a second

2019-07-23 13:20发布

How do I focus a TextBox element on the main form after closing a second form which is opened by calling ShowDialog()?

I have tried to call MainForm.TextBox.Focus() in the closing and closed event of the second form, but this won't focus the textbox.

I am using System.Windows.Forms on the compact framework.

Thanks.

4条回答
淡お忘
2楼-- · 2019-07-23 13:53

ShowDialog() will only return when the second form is closed, so you can write MyTextBox.Select() right after the call.

查看更多
Root(大扎)
3楼-- · 2019-07-23 14:08

From your second form, make a button (or another control) return a DialogResult by going into Properties. When you want the second form to close (ie after you press a button) make it return a specific DialogResult. In your main form you can do this:

if(secondform.ShowDialog() == DialogResult.OK)
{
    textBox.Focus();
    ...
}

Calling ShowDialog() will block until it is closed so you could simply do:

secondform.ShowDialog();
textbox.Focus()

However the first example is for when you only want to make the textbox have focus after you press a certain button or do an action on the second form.

查看更多
劫难
4楼-- · 2019-07-23 14:13
SomeForm form1 = new SomeForm();
form1.ShowDialog();

here you're showing the new form. When you close it, you will execute methods after that, so add

yourTextbox.Focus();

so, its:

SomeForm form1 = new SomeForm();
form1.ShowDialog(); // do what you want in your form, then close it
yourTextbox.Focus();
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-07-23 14:19

ShowDialog means, it's a modal window and the focus won't go back to main form until you close second form. You can set focus back in the same code which you used to open the second form.

SecondFrm.ShowDialog();
Textbox.Focus();
查看更多
登录 后发表回答