1

I want to select the form of my application to edit settings of a textbox in it. I used Form.ActiveForm for this. This works great while the Form is in foreground, but when it's not selected, this doesn't work anymore. Is there a way to get the applications current form, even when it is in background?

EDIT: Here's some code:

var form = Form.ActiveForm as MainForm;
if (form != null)
{
    form.txtChatOutput.Text += p.Data[0] + "\r\n";
}

EDIT 2:

I found a easy solution. Declare a Variable Form myForm; in the class and in your form's Shown event, set it to Form.ActiveForm.

public partial class Form1 : Form
{
    Form myForm;
    ....
    private void Form1_Shown(object sender, EventArgs e)
    {
        myForm = Form.ActiveForm;
    }
}

You can then access your form using myForm, even if it's not selected anymore.

4

2 回答 2

1

虽然中提供的方法Edit 2可行,但还有更直接的方法。

public partial class Form2 : Form
{
    Form1 mainFrm;

    public Form2(Form1 frm)
    {
        InitializeComponent();
        mainFrm = frm;
    }
    ...
}

更改“子”表单的构造函数以获取指示所有者/父表单或主表单的 arg,并将其存储为类 var。为必须始终告知知道父/主表单的表单执行此操作。要以两种方式使用表单,只需上述内容添加为重载 ctor。使用它:

using (Form2 frm = new Form2(this) )
{
    frm.ShowDialog();
}

如果/当您的应用程序是类驱动而不是表单驱动时,您可以Main通过在构造函数中将主表单引用传递给该类来执行类似的操作。

于 2014-11-01T13:25:09.500 回答
0

虽然我不能完全理解你想要达到的目标,但你可以看看

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.findform(v=vs.110).aspx

例如,如果您的表单中有一个文本框,您可以这样做:

//// Get the form that the TextBox control is contained within.
Form myForm = textBoxInstance.FindForm(); 

或者,正如评论中所指出的,遍历所有 OpenForms 并检索您想要的:

// Loop through all the forms
foreach (Form form in Application.OpenForms)
{
   // identify the form you want somehow...
   // example using form name
   if (form.Name == "myForm")
      Form myForm = form;
}
于 2014-10-31T15:22:13.450 回答