简体   繁体   English

关闭form2后,如何选择form1的文本框?

[英]How do I select my form1's textbox after closing form2?

I couldn't find this exact answer anywhere, sorry if it has been answered. 我在任何地方都找不到确切的答案,很抱歉,如果已经回答了。

textbox.select and textbox.focus works great under form1_load but I have a linklabel that opens form2, but closing form2 with my cancel button or the exit button will obviously not select or focus the textbox in form1 again. textbox.select和textbox.focus在form1_load下可以很好地工作,但是我有一个可以打开form2的linklabel,但是用我的“取消”按钮或“退出”按钮关闭form2显然不会再次选择或聚焦于form1中的文本框。

Updated to show code sample of the event that initializes Form2(FormPopup) 更新以显示初始化Form2(FormPopup)的事件的代码示例

private void CreateNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    var popup = new FormPopup();
    popup.ShowDialog();
}

This might not be the best answer, but where you initialize your form 2 (I'm assuming youre doing something like Form2 frm2 = new Form2(); ), I would then under that line, hook up a FormClosed event to that form using frm2.FormClosed += frm2_FormClosed; 这可能不是最好的答案,但是在初始化表单2的地方(我假设您正在执行Form2 frm2 = new Form2(); ),然后在该行下,使用以下命令将FormClosed事件连接到该表单frm2.FormClosed += frm2_FormClosed; . Now you have a method that can detect when form2 closes from your form1, and in this method, you could set the focus of your textbox. 现在,您有了一个可以检测到form2从form1关闭的方法,在这种方法中,您可以设置文本框的焦点。

Code Sample: 代码示例:

private void InitForm2()
{
    Form2 frm2 = new Form2();
    frm2.FormClosed += Form2_FormClosed;
    frm2.Show();
}

private void Form2_FormClosed(object sender, EventArgs e)
{
    textbox1.Focus();
}

Edit: As @Ofir Winegarten pointed out, if you use ShowDialog instead of Show, you could just set the textbox1.Focus() call immediately after that as it will not execute until form2 is closed. 编辑:正如@Ofir Winegarten所指出的,如果使用ShowDialog而不是Show,则可以立即设置textbox1.Focus()调用,因为它在form2关闭之前不会执行。

Code Sample: 代码示例:

private void InitForm2()
{
    Form2 frm2 = new Form2();
    frm2.ShowDialog();

    textbox1.Focus(); //Will not happen until after form2 is closed.
}

Everyone above helped this answer thanks guys. 上面的每个人都帮助了这个答案,谢谢大家。 All I needed was to add myTextBox.Focus(); 我所需要的只是添加myTextBox.Focus(); after my click event that initializes Form2. 在初始化Form2的单击事件之后。 For anyone wondering it is because anything written after ShowDialog(); 对于任何想知道这是因为在ShowDialog()之后写的东西; won't execute until after Form2 is closed. 在关闭Form2之后才能执行。

    private void CreateNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        FormPopup popup = new FormPopup();
        popup.ShowDialog();

        NameBox.Focus();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM