Rand Random
Rand Random

Reputation: 7440

Set owner of OpenFileDialog from window handle

I would like to set the owner of the OpenFileDialog (within namespace Microsoft.Win32 not System.Windows.Forms) but I only have the handle (IntPtr) of the window (the handle doesn't have to be from my application it could be an external).

Is that possible or am I forced to use the OpenFileDialog from System.Windows.Forms?

I want to have the effect of calling the

protected abstract bool RunDialog(IntPtr hwndOwner);

inside the base class CommonDialog, but it's protected. Is there a way around? Could I use reflection to get this method and execute it, or is there a "cleaner" way to do it?

The normal ShowDialog() method only allows a Window, which is something I don't have.

I use this code to set the owner of other window when I only have the handle, but the constructor of WindowInteropHelper only takes a Window and CommondDialog doesn't inherit from Window:

Window window;
IntPtr ownerHwnd;
var wih = new WindowInteropHelper(window);
wih.Owner = ownerHwnd;

Upvotes: 2

Views: 2638

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70671

I suspect this question is still a duplicate of some Stack Overflow question, but I didn't find an obvious closely-matching candidate in a quick search. So…

You can obtain a WPF Window object by casting the RootVisual property value of an HwndSource to Window:

Window IntPtrToWindow(IntPtr hwnd)
{
    HwndSource hwndSource = HwndSource.FromHwnd(hwnd);

    return (Window)hwndSource.RootVisual;
}

See HwndSource Class for more details.

Upvotes: 2

Related Questions