Conflict when opening multiple screens in menuStrip - Visual Studio

0

I have 3 forms.

  • Parent Form (Parent)
  • Child Form (Services)
  • Child Form (Suppliers)

What is happening .. I block the person from trying to open the same form more than once, but when it tries to open another form ( and have another already open ) error: p>

Code that checks if the form is already active - Click event of the menuStrip :

private void serviçosToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            //Verifica se já existe o mesmo formulário aberto para não sobrecarregar de processos iguais

            bool aberto = false;

            foreach (frmCadastroServico f in this.MdiChildren)
                if (f.Name == "frmCadastroServico")
                {
                    f.Activate();
                    aberto = true;
                    break;
                }

                if(!aberto)
                {

                    frmCadastroServico CadastroServico = new frmCadastroServico();
                    CadastroServico.StartPosition = FormStartPosition.CenterParent;
                    CadastroServico.MdiParent = this;
                    CadastroServico.Dock = DockStyle.Fill;
                    CadastroServico.Show();
                }

        }

Error code:

System.InvalidCastException ocorrido
  HResult=0x80004002
  Message=Não é possível converter um objeto do tipo 'Projeto.frmCadastroFornecedores' no tipo 'Projeto.frmCadastroServico'.
  Source=Projeto
  StackTrace:
   em Projeto.frmPrincipal.serviçosToolStripMenuItem1_Click(Object sender, EventArgs e) em C:\Users\willian\source\repos\Projeto\Projeto\frmPrincipal.cs:linha 43
   em System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
   em System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
   em System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
   em System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
   em System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
   em System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
   em System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
   em System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
   em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   em System.Windows.Forms.ToolStrip.WndProc(Message& m)
   em System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.Run(Form mainForm)
   em Projeto.Program.Main() em C:\Users\willian\source\repos\Projeto\Projeto\Program.cs:linha 19

I believe that when I select an option in the menuStrip everything that is open should close before (I'm not sure), does anyone have a solution?

    
asked by anonymous 20.09.2017 / 16:54

1 answer

1

Your foreach is trying to cast on all open forms, this will give Exception because there are other types of open forms that are not of type frmCadastroServico .

Use OfType<T> in your foreach .

Example:

foreach (frmCadastroServico f in this.MdiChildren.OfType<frmCadastroServico>())

Or:

Change the declaration of the variable by var and within foreach try to give a cast to the specified type.

foreach (var f in this.MdiChildren)
{
   var frmServico = f as frmCadastroServico;

   if(frmServico != null)
   {
      // Se entrou quer dizer que este form é do tipo frmCadastroServico
   }

   // Se necessário faça o mesmo para outros forms...
}
    
20.09.2017 / 17:00