控制一种可以多次打开的表格

时间:2018-12-19 07:50:26

标签: c# winforms

假设我打开过相同的表单多次,但我想控制其中一个表单一个fe带有“ hello”作为窗口标题的表单(文本) <-以标识)

我如何做到这一点?

编辑: 这是我想做的事的一个例子(有点复杂,我不善于解释我想做的事)

private void openthesecformfirst_Click(object sender, EventArgs e)
{
    Form2 sec = new Form2();
    sec.Text = "Hi";
    sec.Show();
    //The second form is now opened
}

private void openthesecformsecond_Click(object sender, EventArgs e)
{
    Form2 sec = new Form2();
    sec.Text = "Hello";
    sec.Show();
    //the second form is now opened twice
}

private void changelabelinfirst_Click(object sender, EventArgs e)
{
    //Identified by the title the first opened form2 is supposed to change a label text

    //How do I get this one specifically?
}

private void changelabelinsecond_Click(object sender, EventArgs e)
{
    //Identified by the title the second opened form2 is supposed to change a label text

    //How do I get this one specifically?
}

2 个答案:

答案 0 :(得分:1)

对于OS Windows中的查找窗口,您可以使用Win32 Api中的FindWindowEx,例如:

  1. 因为这是原始的不安全代码,所以您应该从user32.dll导入函数:

    [DllImport("user32.dll", SetLastError = true)] static extern IntPtr 
    FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, 
    string lpszClass, string lpszWindow);
    
    [DllImport("user32.dll", SetLastError = true)]
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr 
    childAfter, 
    string className,  string windowTitle);
    
  2. 导入后,您可以使用如下功能:

     var CaptionTextForLooking = "hello"; // or "Hi"
    
     var foundWindowPtr = 
     FindWindowEx(IntPtr.Zero,IntPtr.Zero,CaptionTextForLooking 
     ,IntPtr.Zero);
    

更多信息,您可以找到here

答案 1 :(得分:-1)

您可以使用Application.OpenForms属性。