如何避免 MDIParent C# Win 表单中显示多个子表单

发布于 2024-11-19 16:53:58 字数 734 浏览 4 评论 0原文

当用户尝试打开已在 MDIParent 中打开的子表单时,我想避免我的子表单多次出现。避免这种情况的一种方法是禁用控制器(在我的例子中为 BUTTON),但我也为此功能提供了一个快捷键(Ctrl+L)。因此,如果用户键入 Ctrl+L,则会打开同一个子窗体,并且我可以看到 MDI 中存在两个子窗体。

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmWebLeads formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

我想避免这种情况。我该怎么做? 在此处输入图像描述

在图像中,您可以看到打开了一个子表单“Name Online Leads”用户第一次使用菜单(LEADS)打开两次,第二次使用快捷键打开。我不希望这种事发生。如果表单已打开,则应避免打开另一个相同的表单...如何做到这一点?

I want to avoid my child form from appearing many times when a user tries to open the child form which is already open in MDIParent. One way to avoid this is by disabling the Controller (in my case BUTTON) but I have given a shortcut key (Ctrl+L) for this function as well. So if the user types Ctrl+L, the same child Form opens and I can see two child forms are in MDI.

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmWebLeads formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

I want to avoid this. How can I do this?
enter image description here

In the image you can see that a child form Name Online Leads is opened twice as the user opened first time using Menu (LEADS) and second time by Shortcut key. I don't want this to happen. If the form is already opened it should avoid opening another same form ... How to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

沒落の蓅哖 2024-11-26 16:53:58

如果我只应该打开一个,我通常这样做的方式是这样的:

//class member for the only formWeblead
frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (formWebLead == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
    }

    formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    formWeblead.Show();
}

the way i usually do it if i am only supposed to have one open is something like:

//class member for the only formWeblead
frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (formWebLead == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
    }

    formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    formWeblead.Show();
}
御守 2024-11-26 16:53:58

在表单 main() 函数中设置它

    InitializeComponent();
     this.WindowState = FormWindowState.Maximized;
     this.ShowInTaskbar = true;

 from_login login = new from_login();
                login.MdiParent=this;
                login.Show();
                pmsnrr.pmsmain = this;  

,这是菜单条光滑事件中的代码

if (this.ActiveMdiChild != null)
            this.ActiveMdiChild.Close();
            frm_companymaster company = new frm_companymaster();
            company.MdiParent = this;
            company.WindowState = FormWindowState.Normal;
            company.Show();

Set this in your form main() function

    InitializeComponent();
     this.WindowState = FormWindowState.Maximized;
     this.ShowInTaskbar = true;

 from_login login = new from_login();
                login.MdiParent=this;
                login.Show();
                pmsnrr.pmsmain = this;  

and this is the code the goes inside your menu strip slick event

if (this.ActiveMdiChild != null)
            this.ActiveMdiChild.Close();
            frm_companymaster company = new frm_companymaster();
            company.MdiParent = this;
            company.WindowState = FormWindowState.Normal;
            company.Show();
听你说爱我 2024-11-26 16:53:58

我个人更喜欢通用实现:

private void ShowOrActivateForm<T>() where T : Form
        {
            var k = MdiChildren.Where(c => c.GetType() == typeof(T)).FirstOrDefault();
            if (k == null) 
            {                    

                k = (Form)Activator.CreateInstance(typeof(T));
                k.MdiParent = this;
                k.Show();
            }
            else
            {
                k.Activate();                
            }            
        }

然后您可以像这样使用它:

ShowOrActivateForm<myForm>();

其中 myForm 是您要创建的表单的类型

I personally prefer a generic implementation:

private void ShowOrActivateForm<T>() where T : Form
        {
            var k = MdiChildren.Where(c => c.GetType() == typeof(T)).FirstOrDefault();
            if (k == null) 
            {                    

                k = (Form)Activator.CreateInstance(typeof(T));
                k.MdiParent = this;
                k.Show();
            }
            else
            {
                k.Activate();                
            }            
        }

Then you can just use it like this:

ShowOrActivateForm<myForm>();

Where myForm is the TYPE of the form you want to create

懵少女 2024-11-26 16:53:58
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    formWeblead formWeblead = null;
    if ((formWeblead = IsFormAlreadyOpen(typeof(frmWebLeads)) == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }
}

public static Form IsFormAlreadyOpen(Type FormType)
{
   foreach (Form OpenForm in Application.OpenForms)
   {
      if (OpenForm.GetType() == FormType)
         return OpenForm;
   }

   return null;
}
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
    formWeblead formWeblead = null;
    if ((formWeblead = IsFormAlreadyOpen(typeof(frmWebLeads)) == null)
    {
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }
}

public static Form IsFormAlreadyOpen(Type FormType)
{
   foreach (Form OpenForm in Application.OpenForms)
   {
      if (OpenForm.GetType() == FormType)
         return OpenForm;
   }

   return null;
}
衣神在巴黎 2024-11-26 16:53:58
    frmWebLeads formWeblead;

    bool isformWebleadOpen =false;

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if(isformWebleadOpen == false)
      {
       formWeblead = new frmWebLeads();
       isformWebleadOpen =true;
       formWeblead.Closed += formWeblead_Closed;
       formWeblead.Show();
      }
   }

   void formWeblead_Closed(object sender, EventArgs e)
   {
     isformWebleadOpen = false;
   }
    frmWebLeads formWeblead;

    bool isformWebleadOpen =false;

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if(isformWebleadOpen == false)
      {
       formWeblead = new frmWebLeads();
       isformWebleadOpen =true;
       formWeblead.Closed += formWeblead_Closed;
       formWeblead.Show();
      }
   }

   void formWeblead_Closed(object sender, EventArgs e)
   {
     isformWebleadOpen = false;
   }
泛滥成性 2024-11-26 16:53:58

当您从菜单打开表单时,变量 frmRep 为 null

frmReportes frmRep = null

...所以我在第一个“if”内添加另一个“if”以验证我的表单是否可见,因为我有另一个表单,那么如果它不可见我创建一个实例并显示表单,但如果可见,我只需使用 Activate()

    private void rToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (frmRep != null)
        {
            if (frmRep.Visible == false)
            {
                frmRep = new frmReportes();
                frmRep.MdiParent = this; frmRep.Show();
            }
            else
            {                    
                frmRep.Activate();
                return;
            }
        }
        else
        {
            frmRep = new frmReportes();
            frmRep.MdiParent = this; 
            frmRep.Show();
        }            
    }

Fists time when you open the form from menu, the variable frmRep is null

frmReportes frmRep = null

...so I add another "if" inside the first "if" to validate my form is visible, because I have another forms, then if its not visible I make an instance and show the form, but if is visible I just use Activate()

    private void rToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (frmRep != null)
        {
            if (frmRep.Visible == false)
            {
                frmRep = new frmReportes();
                frmRep.MdiParent = this; frmRep.Show();
            }
            else
            {                    
                frmRep.Activate();
                return;
            }
        }
        else
        {
            frmRep = new frmReportes();
            frmRep.MdiParent = this; 
            frmRep.Show();
        }            
    }
凝望流年 2024-11-26 16:53:58

最简单的方法是保留对子窗体的引用,并且仅在子窗体不存在时生成一个新窗体。像这样的事情:

class ParentForm : Form { 
    frmWebLeads formWeblead = null;

    //...

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if(formWeblead != null) return;
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

}

您还需要代码在关闭 formWeblead 时将其设置为 null,但我相信您可以弄清楚该部分:)

The easiest way is to keep a reference to the child form, and only spawn a new one if it doesn't already exist. Something like this:

class ParentForm : Form { 
    frmWebLeads formWeblead = null;

    //...

    private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if(formWeblead != null) return;
        formWeblead = new frmWebLeads();
        formWeblead.MdiParent = this;
        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();

    }

}

You also need code to set formWeblead to null when you close it, but I'm sure you can figure that part out :)

堇色安年 2024-11-26 16:53:58
// Implementation of the below class in your MDI Parent
private void openToolStripMenuItem_Click(object sender, EventArgs e) {
            if (SingletonForm.Exists) {
                return;
            } else {
                m_openToolStripMenuItem.Enabled = false;

                SingletonForm form = new SingletonForm();
                form.FormClosed += new FormClosedEventHandler(
                    delegate(object _sender, FormClosedEventArgs _e) {
                        m_openToolStripMenuItem.Enabled = true;
                    });
                form.MdiParent = this;              
                form.Show();
            }
        }


// SingletonForm Class
    using ...
    using System.Threading;

    namespace SingletonForm {

        public partial class SingletonForm : Form, IDisposable {
            static private readonly string m_mutexName = "SingletonForm.SingletonForm";
            private Mutex m_mutex;
            private bool m_disposed;

            public SingletonForm() {
                m_disposed = false;

                // Check to see if there is already a running instance...
                bool owned;
                m_mutex = new Mutex(true, m_mutexName, out owned);
                if (!owned) {
                    // Already running, get out...
                    Close();
                    return;
                }

                InitializeComponent();
            }

            ~SingletonForm() {
                Dispose(false);
            }

            static public bool Exists {
                get {
                    bool owned;
                    using (new Mutex(false, m_mutexName, out owned)) {
                        return !owned;
                    }
                }
            }

            // IDisposable Members
            // --------------------------------------------------------------------------
            #region IDisposable Members
            new public void Dispose() {
                Dispose(true);

                // Use SupressFinalize in case a subclass of this type implements a finalizer.
                GC.SuppressFinalize(this);
            }
            #endregion  // IDisposable Members

            /// <summary>
            /// Note: Comment out the Dispose(bool disposing) implementation in your
            /// SingletonForm.Designer.cs
            /// </summary>
            /// <param name="disposing">true if we are disposing.</param>
            protected override void Dispose(bool disposing) {
                if (disposing && (components != null)) {
                    components.Dispose();
                }

                base.Dispose(disposing);

                // If you need thread safety, use a lock around these 
                // operations, as well as in your methods that use the resource.
                if (!m_disposed) {
                    if (disposing) {
                        // Code to dispose the managed resources held by the class here...
                        if (m_mutex != null) {
                            m_mutex.Dispose();
                            m_mutex = null;
                        }
                    }

                    // Indicate that the instance has been disposed.
                    m_disposed = true;
                }
            }
        };
    };

为了允许 1-n 个实例存在,最好使用信号量。

// Implementation of the below class in your MDI Parent
private void openToolStripMenuItem_Click(object sender, EventArgs e) {
            if (SingletonForm.Exists) {
                return;
            } else {
                m_openToolStripMenuItem.Enabled = false;

                SingletonForm form = new SingletonForm();
                form.FormClosed += new FormClosedEventHandler(
                    delegate(object _sender, FormClosedEventArgs _e) {
                        m_openToolStripMenuItem.Enabled = true;
                    });
                form.MdiParent = this;              
                form.Show();
            }
        }


// SingletonForm Class
    using ...
    using System.Threading;

    namespace SingletonForm {

        public partial class SingletonForm : Form, IDisposable {
            static private readonly string m_mutexName = "SingletonForm.SingletonForm";
            private Mutex m_mutex;
            private bool m_disposed;

            public SingletonForm() {
                m_disposed = false;

                // Check to see if there is already a running instance...
                bool owned;
                m_mutex = new Mutex(true, m_mutexName, out owned);
                if (!owned) {
                    // Already running, get out...
                    Close();
                    return;
                }

                InitializeComponent();
            }

            ~SingletonForm() {
                Dispose(false);
            }

            static public bool Exists {
                get {
                    bool owned;
                    using (new Mutex(false, m_mutexName, out owned)) {
                        return !owned;
                    }
                }
            }

            // IDisposable Members
            // --------------------------------------------------------------------------
            #region IDisposable Members
            new public void Dispose() {
                Dispose(true);

                // Use SupressFinalize in case a subclass of this type implements a finalizer.
                GC.SuppressFinalize(this);
            }
            #endregion  // IDisposable Members

            /// <summary>
            /// Note: Comment out the Dispose(bool disposing) implementation in your
            /// SingletonForm.Designer.cs
            /// </summary>
            /// <param name="disposing">true if we are disposing.</param>
            protected override void Dispose(bool disposing) {
                if (disposing && (components != null)) {
                    components.Dispose();
                }

                base.Dispose(disposing);

                // If you need thread safety, use a lock around these 
                // operations, as well as in your methods that use the resource.
                if (!m_disposed) {
                    if (disposing) {
                        // Code to dispose the managed resources held by the class here...
                        if (m_mutex != null) {
                            m_mutex.Dispose();
                            m_mutex = null;
                        }
                    }

                    // Indicate that the instance has been disposed.
                    m_disposed = true;
                }
            }
        };
    };

Would have been nice to use semaphores instead in order to allow 1-n instances to exist.

眉目亦如画i 2024-11-26 16:53:58

这是我为在单击 MDIParent 中的菜单时仅调用打开一个表单而创建的“方法”。希望这个“方法”能够帮助到您!

用法:甚至在 ToolStripMenuItems 上。

Form1 frm1 = new Form1();
CheckActiveChildForm(frm1,"myForm");

//myForm is the Text of Form1
private void CheckActiveChildForm(Form FormControl, string FormExists)
{
    int h = 0;
    if (MdiChildren.Count() == 0)
    {
        //Form2 childF = new Form2();
        FormControl.MdiParent = this;
        FormControl.Show();
    }

    if (MdiChildren.Count() > 0)
    {
        for (int i = 0; i < MdiChildren.Count(); i++)
        {
            if (MdiChildren.ElementAt(i).Text == FormExists)
            {
                h = 1;
            }
        }
    }

    if (h == 0)
    {
        FormControl.MdiParent = this;
        FormControl.Show();
    }
}

Here is the "Method" that I created for Calling open only one form when u click on Menu in MDIParent. Hope this "Method" can help you!

Usage: On Even ToolStripMenuItems.

Form1 frm1 = new Form1();
CheckActiveChildForm(frm1,"myForm");

//myForm is the Text of Form1
private void CheckActiveChildForm(Form FormControl, string FormExists)
{
    int h = 0;
    if (MdiChildren.Count() == 0)
    {
        //Form2 childF = new Form2();
        FormControl.MdiParent = this;
        FormControl.Show();
    }

    if (MdiChildren.Count() > 0)
    {
        for (int i = 0; i < MdiChildren.Count(); i++)
        {
            if (MdiChildren.ElementAt(i).Text == FormExists)
            {
                h = 1;
            }
        }
    }

    if (h == 0)
    {
        FormControl.MdiParent = this;
        FormControl.Show();
    }
}
风渺 2024-11-26 16:53:58

您可以检查当前打开的表格来实现这一点:

if (Application.OpenForms.Count == 1) {
    ReportProductDetails Report9 = new ReportProductDetails();
    Report9.MdiParent = this;
    Report9.Show();
    Report9.Activate();
}
else {
    MessageBox.Show("Sorry!Close the All the Exist Form,Before open this Form", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

You could check current open forms to achieve that:

if (Application.OpenForms.Count == 1) {
    ReportProductDetails Report9 = new ReportProductDetails();
    Report9.MdiParent = this;
    Report9.Show();
    Report9.Activate();
}
else {
    MessageBox.Show("Sorry!Close the All the Exist Form,Before open this Form", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
嘿咻 2024-11-26 16:53:58

我使用这个解决方案,有一个小技巧

frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (formWebLead == null || formWebLead.isAccessible == false)
        {
            formWeblead = new frmWebLeads();
            formWeblead.MdiParent = this;
        }

        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }

I use this solution, with a little trick

frmWebLeads formWebLead = null;

private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (formWebLead == null || formWebLead.isAccessible == false)
        {
            formWeblead = new frmWebLeads();
            formWeblead.MdiParent = this;
        }

        formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        formWeblead.Show();
    }
两仪 2024-11-26 16:53:58
    private void mnuMyForm_Click(object sender, EventArgs e) // click to open MyForm
    {
        foreach (Form item in this.MdiChildren) // check all opened forms
        {
            if (item.Name == "MyFormName") // check by form name if it's opened
            {
                item.BringToFront(); // bring it front
                return; //exit
            }
        }

        // if MyForm is not opened
        // you know what it is
        MyForm frm = new MyForm();
        frm.MdiParent = this;
        frm.Show();
    }
    private void mnuMyForm_Click(object sender, EventArgs e) // click to open MyForm
    {
        foreach (Form item in this.MdiChildren) // check all opened forms
        {
            if (item.Name == "MyFormName") // check by form name if it's opened
            {
                item.BringToFront(); // bring it front
                return; //exit
            }
        }

        // if MyForm is not opened
        // you know what it is
        MyForm frm = new MyForm();
        frm.MdiParent = this;
        frm.Show();
    }
醉城メ夜风 2024-11-26 16:53:58

防止 MDI 表单中出现相同子表单的代码

private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
  frmMaterial newMDIChild = new frmMaterial();
  bool opened = false;
  foreach (Form OpenForm in Application.OpenForms)
  {
    if (OpenForm.GetType() == typeof(frmMaterial))
    {
      OpenForm.Activate();//to bring the activated form to the front
      opened = true;
    }
  }
  if (opened==false)
  {
    // Set the Parent Form of the Child window.
    newMDIChild.MdiParent = this;
    //newMDIChild.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    // Display the new form.
    newMDIChild.Show();
  }
}

The code which prevents the same child form in an MDI form

private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
  frmMaterial newMDIChild = new frmMaterial();
  bool opened = false;
  foreach (Form OpenForm in Application.OpenForms)
  {
    if (OpenForm.GetType() == typeof(frmMaterial))
    {
      OpenForm.Activate();//to bring the activated form to the front
      opened = true;
    }
  }
  if (opened==false)
  {
    // Set the Parent Form of the Child window.
    newMDIChild.MdiParent = this;
    //newMDIChild.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    // Display the new form.
    newMDIChild.Show();
  }
}
夜未央樱花落 2024-11-26 16:53:58

防止多个子实例的最简单方法:

 private void Showforms(Form frm)
 {
   if (this.ActiveMdiChild==null)
   {
      frm.MdiParent = this;               
      frm.Show();
   }
 }

然后像这样调用它:

Form1 frm = new Form1();
Showforms(frm);

The simplest ways of preventing multiple instance of child:

 private void Showforms(Form frm)
 {
   if (this.ActiveMdiChild==null)
   {
      frm.MdiParent = this;               
      frm.Show();
   }
 }

Then call it like this:

Form1 frm = new Form1();
Showforms(frm);
守护在此方 2024-11-26 16:53:58

防止多个子实例的最简单方法

private void Showforms(Form frm)
{
    if (this.ActiveMdiChild==null)
    {
        frm.MdiParent = this;
        frm.Show();
    }  
}

the simpleist ways of preventing multiple instance of child

private void Showforms(Form frm)
{
    if (this.ActiveMdiChild==null)
    {
        frm.MdiParent = this;
        frm.Show();
    }  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文