【问题标题】:Control one form that is opened multiple times控制一个表单多次打开
【发布时间】:2018-12-19 07:50:26
【问题描述】:

假设我打开了同一个表单多次,但我想控制其中一个f.e 的窗口标题为“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?
}

【问题讨论】:

  • 欢迎来到stackoverflow。请花一分钟时间回答tour,尤其是How to Ask,以及edit您的问题。
  • 为什么不保留打开表单的参考?
  • 您是否只是打开表格并放弃参考资料?或者 oyu 是否将它们列在列表中?如果您将它们放在 List 或类似列表中,则可以使用 Linq 查找特定的。
  • 您应该保留对您打开的每个表单的引用并使用它来更新文本。您可以使用两个字段级变量或列表或字典。

标签: c# winforms


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用Application.OpenForms 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      相关资源
      最近更新 更多