Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Window.Owner using hWnd

Tags:

c#

wpf

winapi

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.

like image 589
Drahcir Avatar asked Dec 12 '12 15:12

Drahcir


2 Answers

Use WindowInteropHelper:

Window dialog = new MyDialog();
WindowInteropHelper wih = new WindowInteropHelper(dialog);
wih.Owner = ownerHwnd;
dialog.ShowDialog();
like image 125
Douglas Avatar answered Nov 10 '22 11:11

Douglas


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);
like image 27
Drahcir Avatar answered Nov 10 '22 11:11

Drahcir