SetParent not Working InvalidOperationException

2k Views Asked by At

I recently tried to work on an old project I had an i am not able to get the setparent to work it keeps giving me the "InvalidOperationException" error, here is the code:

private void button1_Click(object sender, EventArgs e)
    {
        Process proc = Process.Start("calc.exe");
        proc.WaitForInputIdle();
        Thread.Sleep(500);
        SetParent(proc.MainWindowHandle, this.Handle);
    }

Its being called with a button and when it tries to set the parent it errors out. Everything i can find online say that my code is right.

1

There are 1 best solutions below

3
41686d6564 On

This code below is working fine on my side (Please check the declaration of your Windows API function SetParent):

    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

    private void button1_Click(object sender, EventArgs e)
    {
        Process proc = Process.Start("calc.exe");
        proc.WaitForInputIdle();
        Thread.Sleep(500);
        SetParent(proc.MainWindowHandle, this.Handle);
    }

Result:

enter image description here

Hope that helps :)