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;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s