Wednesday, August 18, 2010

WPF Modal Dialog when owner is IWin32Window

Today I was working on a plugin for Windows Live Photo Gallery, using WPF, and ran into an issue where I could not seem to set up modal dialog behavior. When a user opened up my plugin the task bar would have two entries, Windows Live Photo Gallery (WLPG), and my plugin. If a user selected the WLPG our plugin would be hidden behind the WLPG window.

However, I noticed other plugins made the border flash when trying to go back to WLPG without closing the plugin. I wanted the modal behavior in my plugin also. Simply using a WPF Window's .ShowDialog does not do the trick. This is because the WLPG is a IWin32Window, not a System.Windows.Window. WindowInteropHelper to the rescue!!!

GET TO THE POINT OF HOW TO DO IT! OK, OK, I hear you. So to make this simple make the following assumption. You have a WPF window named wpfWindow. You want to show wpfWindow as a modal dialog of the IWin32Window. Code the following:

//BEGIN CODE Snippet
//Use WindowInteropHelper to the wpfWindow
WindowInteropHelper helper = new WindowInteropHelper(wpfWindow);

//Get the process containing the IWin32Window
Process procs = Process.GetCurrentProcess();
IntPtr hwnd = procs.MainWindowHandle;

//Set the owner so it behaves like a true Modal Dialog
helper.Owner = hwnd;
wpfWindow.ShowDialog();

//End code snippet


That is all.
Cheers!
Bryon

1 comment:

  1. Fantastic! Very straightforward. All the information I found on this so far required writing wrapper classes and such. This saved me a lot of hastle and works like a treat.

    ReplyDelete