Drahcir
Drahcir

Reputation: 11972

Set Window.Owner using hWnd

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.

Upvotes: 11

Views: 7854

Answers (2)

Drahcir
Drahcir

Reputation: 11972

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

Upvotes: 10

Douglas
Douglas

Reputation: 54897

Use WindowInteropHelper:

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

Upvotes: 16

Related Questions