Link to home
Start Free TrialLog in
Avatar of gvector1
gvector1

asked on

Regain form instance from handle

Is there any way to create and instance of a form from a handle?

Ex.

Form myForm = new Form();
IntPtr ptr = myForm.handle;

........
//This is where I would like to be able to create an instance of that form so that I can regain managed control of the form.  The IntPtr is used as a holder for a particular form.  When created, the handle is stored in the IntPtr.  Later on when an instance of that form is created, if the IntPtr is holding a value, I would like to pull that instance and make it active instead of creating another instance.  So can an instance of a form be created from an Handle?

Form anotherform = ptr;  

ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

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
Avatar of AlexFM
AlexFM

Such problem exists when we must find managed class reference from unmanaged callback function using context information. Context information is usually 32-bits integer passed to unmanaged function. Having this number we must call managed function from class instance which initiated callback.
This is done using GCHandle structure and not window handle. If this is your case, you can see how it is done in EnumWindows sample, GCHandle MSDN description. I can give you additional information if you need.
Avatar of gvector1

ASKER

Okay, if I just keep an instance of my form around for use later how can I bring it to the front later.
Ex.

If my form is minimized and I change the windowstate to normal, it will come up and display in the front, but if my form is in the background, how can I cause it to come to the foreground???
Nevermind.  All I have to do is focus the window.
Here is an example that illustrates it further:

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

        private Form frm = new Form();
       
        private void Form1_Load(object sender, EventArgs e)
        {
            frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
        }

        void frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            frm = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (frm == null)
            {
                frm = new Form();
            }
            if (frm.WindowState == FormWindowState.Minimized)
            {
                frm.WindowState = FormWindowState.Normal;
            }
            frm.Show();
            frm.BringToFront();
        }

    }