簡體   English   中英

將C ++ Hwnd傳遞給C#dll

[英]Pass C++ Hwnd to C# dll

我正在從我的C ++類顯示ac#對話框。 我想將在C ++代碼中創建的窗口設置為C#對話框的父窗口。 我在調用C#對話框的ShowDialog方法之前傳遞了hwnd。 我應該如何在我的C#方法中使用此hwnd; c#方法的原型和代碼應該是什么?

謝謝

您可以簡單地將其公開為IntPtr。 使用NativeWindow.AssignHandle()創建所需的IWin32Window。 完成后釋放ReleaseHandle()。

確保絕對安全不會有任何傷害,您將想知道何時出於任何原因關閉了父級,並且擔心例外安全性。 啟發這個輔助課程:

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);
}

未經測試,應該接近。

這就是我做的

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

很棒!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM