11

In my WPF/C# app I'm creating a dialog window using code like the below:

Window dialog = new MyDialog() as Window;
dialog.Owner = Window.GetWindow(this);
dialog.ShowDialog();

How can I set the dialog owner to the hWnd of another applications window?

The functionality that I need is just to have the "Owner Window" to be blocked while the dialog is visible.

simonc
  • 41,632
  • 12
  • 85
  • 103
Drahcir
  • 11,772
  • 24
  • 86
  • 128

2 Answers2

15

Use WindowInteropHelper:

Window dialog = new MyDialog();
WindowInteropHelper wih = new WindowInteropHelper(dialog);
wih.Owner = ownerHwnd;
dialog.ShowDialog();
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • 2
    This is working to set the owner, but unfortunately it doesn't block user input to the window. Is there a way to do that? – Drahcir Dec 12 '12 at 15:33
10

I have found a solution to block the "Owner Window". The first part of the code is from Douglas answer, the rest is using a call to the WinAPI EnableWindow method:

Window dialog = new MyDialog();
WindowInteropHelper wih = new WindowInteropHelper(dialog);
wih.Owner = ownerHwnd;

//Block input to the owner
Windows.EnableWindow(ownerHwnd, false);

EventHandler onClosed = null;
onClosed = (object sender, EventArgs e) =>
{
    //Re-Enable the owner window once the dialog is closed
    Windows.EnableWindow(ownerHwnd, true);

    (sender as Window).closed -= onClosed;
};

dialog.Closed += onClosed;
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
dialog.ShowActivated = true;
dialog.Show();

//Import the EnableWindow method
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
Drahcir
  • 11,772
  • 24
  • 86
  • 128