c# - 如何让 .NET 4 应用程序的主窗体出现在最前面?

标签 c# winforms .net-4.0

我有一个 .NET 4 WinForm 应用程序。我在打开子窗体的主窗体上有一个按钮。子窗体具有焦点。当子窗体打开时,如果我单击主窗体,主窗体将获得焦点,但子窗体仍位于主窗体之上。

即使子窗体打开,我怎样才能让主窗体出现在最前面?

这是我的两种形式的示例代码:

using System;
using System.Windows.Forms;

namespace WinTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var form = new Form2();

            form.Show(this);
        }
    }
}

using System.Windows.Forms;

namespace WinTest
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    }
}

根据下面 Kumar 的回答,我更新了我的主表单如下:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WinTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            _FormList = new List<Form>();
        }

        private List<Form> _FormList;

        private void button1_Click(object sender, EventArgs e)
        {
            var form = new Form2();
            form.FormClosed += Form_FormClosed;
            _FormList.Add(form);
            form.Show();
        }

        private void Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            _FormList.Remove((Form)sender);
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            foreach (var form in _FormList)
            {
                form.Visible = WindowState != FormWindowState.Minimized;
            }
        }
    }
}

这现在按预期工作。

最佳答案

这样做

form.Show(); 

代替

form.Show(this); 

参数设置要显示的表单的父级。父表单将在他的子表单下。

关于c# - 如何让 .NET 4 应用程序的主窗体出现在最前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5302496/

相关文章:

c# - TDD 与 DDD MVC

javascript - 动态地将媒体查询添加到页面并覆盖从应用程序端生成的 html 中的样式

wpf - 如果 Prism 模块崩溃会怎样?应用还稳定吗?

c# - 使用多个 http 请求通过并行任务获取数据来检索部分内容

c# - 错误 : 'The system cannot find the file specified.' when trying to access certificate

c# - 更新绑定(bind)进度条

c# - 使用 Tesseract ocr 时调用的目标抛出异常

c# - 如何在 C# 中移动 PictureBox?

c# - 如何防止RichTextBox Append 导致OutOfMemory?

c# - 选择/拾取在 Direct2D 中应该如何工作?