简体   繁体   中英

Pass C++ Hwnd to C# dll

I am showing ac# 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

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.

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!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM