将C++Hwnd传递到C#dll
Pass C++ Hwnd to C# dll
我正在显示c++类中的一个c#对话框。我想将在C++代码中创建的窗口设置为C#对话框的父窗口。在调用C#对话框的ShowDialog方法之前,我将传入hwnd。我应该如何在我的C#方法中使用这个hwnd;c方法的原型和代码应该是什么?
感谢
您可以简单地将其公开为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);
}
未测试,应该接近。
就是这样做的
var helper = new WindowInteropHelper(myWpfWind);
helper.Owner = hWnd; // hWnd is the IntPtr handle of my C++ window
myWpfWind.ShowDialog();
效果很好!!!
相关文章:
- 挂起和取消挂起一个文件DLL
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 导入库可以跨dll版本工作吗
- 从C++dll访问C#中的一行主要参数
- 链接到自行创建的dll失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- C++:将外部库链接到dll库
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 不同的Visual Studio版本中缺少.dll
- 从DLL中删除类的实例
- 如何包装第三方DLL在R中使用
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 如何在ATL DLL中获取HWND(用于SendMessage或PostMessage)
- 将C++Hwnd传递到C#dll
- 一旦我从Win32 DLL中获得HWND,我可以获得本机窗口的坐标(即使窗口移动)