Link to home
Start Free TrialLog in
Avatar of elmbrook
elmbrook

asked on

open form from string form name and check if the form is already opened or not c#

Hi,

I am trying to open a form from string form name
and it works
then i want to check if the form is already opened or not

this is my button click event

_projectname = "myCollections";
_formname = "myGames";

object myobject = new object();
Type myForm = Assembly.GetExecutingAssembly().GetType(_projectname + ".Forms." + _formname);

if (myForm != null)
{
     myobject = Activator.CreateInstance(myForm);

     //PROBLEM HERE
     Form checkform = myglobal_methods.IsFormAlreadyOpen(typeof((Form)myobject)));

     ((Form)myobject).Show();
}

then i have a method to check if the form is already opened

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

the problem is that (Form)myobject is not a Form.

How i suppose to handle this?


Thank you
Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

Pass the ObjectHandle instance you get from Activator.GetInstance method to IsFormAlreadyOpen.
In IsFormAlreadyOpen iterate thru each open form and create an instance of ObjectHandle from openform.Handle and compare the objects
Avatar of elmbrook
elmbrook

ASKER

Ho you suppose to do that?
I already do that

//PROBLEM HERE
Form checkform = myglobal_methods.IsFormAlreadyOpen(typeof((myobject ));

not working
You are sending typeof(myobject) instead send myobject itself
Form checkform = myglobal_methods.IsFormAlreadyOpen(myobject);
public static Form IsFormAlreadyOpen(ObjectHandle FormType)
{
     ObjectHandle ha = null;
     foreach (Form OpenForm in Application.OpenForms)
     {
          ha = new ObjectHandle(OpenForm.Handle);
         if (ha.Equals(FormType))
          return OpenForm;
      }
     return null;
}  
Hi got an error here saying that

cannot convert from object to system.runtime.remoting.objecthandle
replace object myobject = new object(); with ObjectHandle myobject = null;
ASKER CERTIFIED SOLUTION
Avatar of japete
japete

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial