Modal WPF Windows And The Visual Studio Window

So I needed to show a modal WPF window from inside a Visual Studio Extension. To do that, I needed two thing: 1. a handle of the Visual Studio window and 2. a conversion from the window handle to something compatible with WPF. Long story short – voila:

public static bool ShowDialog(Window dialog)
{
    // Get the top-level Visual Studio object.
    var dte = (DTE)Package.GetGlobalService(typeof(SDTE));

    // Get the handle to Visual Studio's main window
    var hwnd = dte.MainWindow.HWnd;

    // WindowInteropHelper converts betwen WPF and Win32 
    var helper = new WindowInteropHelper(dialog);

    // Now we can use the main window's handle as the owner of our dialog
    helper.Owner = new IntPtr(hwnd);

    // From here on, everything is pure WPF again
    var dialogResult = dialog.ShowDialog();
    return dialogResult.HasValue && dialogResult.Value;
}

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

Leave a Reply

Your email address will not be published. Required fields are marked *