2

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;
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • I think you're stuffed, as the dialogs are sealed so you can't even derive from them and inject your own handle when `RunDialog` is called. The WinForms versions wrap the same native dialogs, so that's probably the best option. – Charles Mager Jul 06 '15 at 13:16
  • You can cheat and use MethodInfo.Invoke() to execute RunDialog. Trying that hard to avoid the winforms version isn't very useful. – Hans Passant Jul 08 '15 at 18:05

1 Answers1

2

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.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • 1
    Does this work with external hwnds? So for example I write an add-in for an PDF reader (or other random program) and call my C# method with this code do I really get a WPF Window object? – Rand Random Jul 08 '15 at 17:32
  • 1
    That depends on what you mean by "external". For sure, it should work for any HWND from the same process. Sharing handles across processes can be tricky, but assuming you have a valid HWND that you would otherwise be able to use (e.g. send messages to), it would probably work there as well. Easy enough for you to try though. – Peter Duniho Jul 08 '15 at 17:34
  • 1
    Will give it a try, thanks for the answer gona come back eventually. And yeah I meant from different processes. – Rand Random Jul 08 '15 at 17:35