我正在展示我的 C++ 类(class)中的 C# 对话框。我想将在我的 C++ 代码中创建的窗口设置为我的 C# 对话框的父窗口。在调用 C# 对话框的 ShowDialog 方法之前,我传入了 hwnd。我应该如何在我的 C# 方法中使用这个 hwnd; c#方法的原型(prototype)和代码具体应该是什么?
谢谢
最佳答案
您可以简单地将其公开为 IntPtr。使用 NativeWindow.AssignHandle() 创建您需要的 IWin32Window。完成后释放 Handle()。
让它绝对安全不会有什么坏处,你会想知道父级何时因任何原因关闭并且异常安全是一个问题。启发这个助手类:
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);
}
未经测试,应该接近。
关于c# - 将 C++ Hwnd 传递给 C# dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744155/