Search code examples
c#wpf.net-8.0setparent

How to set SetParent in WPF on .NET 8?


I want to set a SetParent in my WPF application, but when I try to do that, it doesn't work. I try it in .NET 8.

The program where I want to set the parent is calc.exe.

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Process process = Process.Start("calc.exe");

    // Find the handle of the external window
    IntPtr externalWindowHandle = process.MainWindowHandle;

    if (externalWindowHandle != null)
    {
        // Reparent the external window into the WPF application
        SetParent(externalWindowHandle, new WindowInteropHelper(this).Handle);
    }
    else
    {
        MessageBox.Show("External window not found.");
    }
}

I am expecting the view of calc.exe to appear inside my WPF view.


Solution

  • The process' main window handle may not be immediately available. You should block until it's ready:

    Process process = Process.Start("calc.exe");
    
    // Wait until the process finishes creating the window handle
    process.WaitForInputIdle();
    
    // Find the handle of the external window
    IntPtr externalWindowHandle = process.MainWindowHandle;