WAQ
WAQ

Reputation: 2626

Pass C++ Hwnd to C# dll

I am showing a c# dialog from my C++ class. I want to set the window that is created in my C++ code as the parent of my C# dialog. I am passing in the hwnd before calling the ShowDialog method of C# dialog. How should I use this hwnd in my C# method; what should be the prototype and code of the c# method in particular?

Thanks

Upvotes: 0

Views: 2894

Answers (2)

WAQ
WAQ

Reputation: 2626

This is how I did it

var helper = new WindowInteropHelper(myWpfWind);
helper.Owner = hWnd; // hWnd is the IntPtr handle of my C++ window
myWpfWind.ShowDialog();

Works great!!!

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941645

You can simply expose it as an IntPtr. Use NativeWindow.AssignHandle() to create the IWin32Window that you'll need. ReleaseHandle() when you're done.

It won't hurt to make it absolutely safe, you'll want to know when the parent is closed for any reason and exception safety is a concern. Inspiring this helper class:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class UnmanagedDialogParent : NativeWindow {
    private Form dialog;
    public DialogResult ShowDialog(IntPtr parent, Form dlg) {
        if (!IsWindow(parent)) throw new ArgumentException("Parent is not a valid window");
        dialog = dlg;
        this.AssignHandle(parent);
        DialogResult retval = DialogResult.Cancel;
        try {
            retval = dlg.ShowDialog(this);
        }
        finally {
            this.ReleaseHandle();
        }
        return retval;
    }

    protected override void WndProc(ref Message m) {
        if (m.Msg == WM_DESTROY) dialog.Close();
        base.WndProc(ref m);
    }

    // Pinvoke:
    private const int WM_DESTROY = 2;
    [DllImport("user32.dll")]
    private static extern bool IsWindow(IntPtr hWnd);
}

Untested, ought to be close.

Upvotes: 2

Related Questions