【问题标题】:How to Focus to another form in C#如何在 C# 中聚焦到另一个表单
【发布时间】:2017-05-31 07:25:04
【问题描述】:

我有一个程序可以打开两个表格 我想当我在clickForm1 然后FocusForm2

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

但这不起作用,我的代码有什么问题?

编辑: 我在 cmets 上发现 @moguzalp 已经回答了 Here

【问题讨论】:

  • this
  • 不要创建新实例它会起作用
  • 感谢它的工作@moguzalp 你能把这个作为答案发布吗?
  • @KiraSama 已经在相关问答中给出了答案。如果你愿意,你可以点赞

标签: c# winforms


【解决方案1】:

首先,Form2 永远不可见。

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

如果该表单在您的代码中可见,则意味着您需要获得相同的引用并针对它调用 Focus()


编辑:


那么您需要对该表单进行引用。 在某些时候,您创建了该表单并将其分配给一个变量/字段或类似的东西。

您需要致电FocusActivate 反对。

例子:

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();
    }


}

【讨论】:

  • 对不起,我说我已经展示了 Form2,我想在点击 Form1 时专注于它
  • 您的代码正在运行,但您能解释一下如何在不再次显示表单的情况下进行操作吗?
【解决方案2】:

如果您可以打开一个表单,请尝试找到它:

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();
}

【讨论】:

    【解决方案3】:

    如果你想展示你的 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();
    }
    

    【讨论】:

    • 不,我说我已经向他们展示了,但是当我点击 Form1 时我想专注于 Form2
    【解决方案4】:

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

    您必须保留对打开的表单的引用,然后使用Focus 或者可能更好的是Activate

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

    1. 添加一个字段来保存Form2的当前引用
    2. 显示表单时保存。
    3. 对焦时使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2011-05-01
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多