Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在C中聚焦到另一个窗体_C#_Winforms - Fatal编程技术网

C# 如何在C中聚焦到另一个窗体

C# 如何在C中聚焦到另一个窗体,c#,winforms,C#,Winforms,我有一个打开两个窗体的程序 我想当我点击Form1时 然后关注Form2 但这不起作用,我的代码怎么了 编辑: 我发现@moguzalp在评论中已经回答了我的问题,首先,表单2是不可见的 private void Form1_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.Show(); frm2.Focus(); } 如果该表单在代码中是可见的,则意味着您需要获得相同的引用,

我有一个打开两个窗体的程序 我想当我点击Form1时 然后关注Form2

但这不起作用,我的代码怎么了

编辑:
我发现@moguzalp在评论中已经回答了我的问题,首先,表单2是不可见的

    private void Form1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();
    frm2.Focus();
}
如果该表单在代码中是可见的,则意味着您需要获得相同的引用,并对其调用焦点

编辑:

然后你需要有一个对该表单的引用。 在某个时刻,您创建了该表单并将其分配给VARABLE/字段或类似的内容

你需要呼叫焦点或针对它激活

例如:

在Form1内部创建Form2实例时:

public class Form1 : Form 
{
   private Form _frm2;


   //That code you probably have somewhere. You need to make sure that this Form instance is accessible inside the handler to use it.
   public void Stuff() {
     _frm2 = new Form2();
     _frm2.Show();
   }

    private void Form1_Click(object sender, EventArgs e)
    {
        _frm2.Focus(); //or _frm2.Activate();
    }


}

如果你想展示你的frm2,你应该调用frm2.Show;或frm2.ShowDialog

此外,在“显示”调用之前,您可以将frm2.TopMost设置为true;如果您希望此表单位于顶部

因此可能是:

private void Form1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.TopMost = true;
    frm2.Show();
}

如果您已经在其他地方打开了表单,那么此代码将不起作用,因为它是Form2的新实例,而不是已打开的实例

您必须保留对已打开表单的引用,然后使用Focus或更好的方法激活它

如果表单是从Form1中打开的,则:

添加用于保存Form2当前引用的字段 显示表单时保存它。 聚焦时使用它

private Form2 currentForm2;
....
this.currentForm2 = new Form2();
this.currentForm2.Show();
...
...
this.currentForm2.Activate();

如果可以打开表单,请尝试查找它:


看到了吗?不要创建新实例它会工作的谢谢它的工作@moguzalp你能把这个作为答案发布吗?@KiraSama的答案已经在相关问答中给出了。如果你愿意,你可以投票。我说我已经向他们展示了,但我想在点击Form1时关注Form2。对不起,我说我已经向Form2展示了,我只想关注它当我点击Form1时,你的代码正在工作,但是你能解释一下我如何在不再次显示表单的情况下完成它吗?
private Form2 currentForm2;
....
this.currentForm2 = new Form2();
this.currentForm2.Show();
...
...
this.currentForm2.Activate();
using System.Linq;

...

// Do we have any Form2 instances opened?
Form2 frm2 = Application
  .OpenForms
  .OfType<Form2>()
  .LastOrDefault(); // <- If we have many Form2 instances, let's take the last one 

// ...No. We have to create and show Form2 instance
if (null == frm2) {
  frm2 = new Form2();
  frm2.Show(); 
}
else { // ...Yes. We have to activate it (i.e. bring to front, restore if minimized, focus)
  frm2.Activate();
}