c# - 将 HWND 转换为 IntPtr (CLI)

标签 c# mfc c++-cli command-line-interface

我的 C++ MFC 代码中有一个 HWND,我想将此 HWND 传递给 C# 控件并将其作为 IntPtr 获取。

我的代码有什么问题,我该如何正确执行? (我认为使用 CLI 指针有问题,因为我得到一个错误,它无法从 System::IntPtr^ 转换为 System::IntPtr。但我不知道如何使它全部正常工作。 ..)

我的 C++ MFC 代码:

HWND myHandle= this->GetSafeHwnd();
m_CLIDialog->UpdateHandle(myHandle);

我的 C# 代码:

public void UpdateHandle(IntPtr mHandle)
{
   ......
}

我的 CLI 代码:

void CLIDialog::UpdateHandle(HWND hWnd)
{
   System::IntPtr^ managedhWnd = gcnew System::IntPtr();
   HWND phWnd; // object on the native heap

   try
   {

       phWnd = (HWND)managedhWnd->ToPointer();
        *phWnd = *hWnd; //Deep-Copy the Native input object to Managed wrapper.

       m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);
    }

当前发生在 m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);

上的错误(无法从 IntPtr^ 转换为 IntPtr)

如果我将 CLI 代码更改为:

void CLIDialog::UpdateHandle(HWND hWnd)
{
   System::IntPtr managedhWnd;
   HWND phWnd; // object on the native heap

   try
   {

       phWnd = (HWND)managedhWnd.ToPointer();
        *phWnd = *hWnd; //Deep-Copy the Native input object to Managed wrapper.

       m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);
    }

所以在这种情况下,在 C# 中获得的值为 0。

如何让它正常工作?

最佳答案

要从 HWND(它只是一个指针)转换为 IntPtr,您只需调用它的构造函数,您不需要 gcnew,因为它是一个值类型。 因此,这应该可以将 HWND 从 native 传递到托管:

void CLIDialog::UpdateHandle( HWND hWnd )
{
  IntPtr managedHWND( hwnd );
  m_pManagedData->CSharpControl->UpdateHandle( managedHWND );
}

这是一个您可以从托管代码调用并从 native 代码中获取 native HWND 的函数:

void SomeManagedFunction( IntPtr hWnd )
{
  HWND nativeHWND = (HWND) hWnd.ToPointer();
  //...
}

关于c# - 将 HWND 转换为 IntPtr (CLI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14334261/

相关文章:

c# - 添加jquery.unobtrusive-ajax.js引用后上传为空

visual-studio-2008 - 什么时候应该在 gcnew 分配的对象上调用 delete?

c# - FakeItEasy 属性未更新

c# - 形成 MVC/ Controller / Action 链接的最佳实践

c++ - 使用运算符 '<<' 设计一个 C++ 记录器

c++ - MFC 和线程。跳过文档/ View 并制作我自己的解决方案?

c++ - 如何释放在 C++ 中加载的 DotNet 程序集

c++ - Visual C++ 项目引用的新手帮助

c# - DllImport vs LoadLibrary,最好的方法是什么?

c++ - 从工具栏获取 Internet Explorer 中当前页面的地址