转换HWND到的IntPtr(CLI)(Convert HWND to IntPtr (CLI))

2019-07-18 05:11发布

我有一个HWND在我的C ++ MFC代码,我想这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);
    }

错误发生目前上(不能从IntPtr的^到IntPtr的转换) m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);

如果我改变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。

我怎样才能使其正常工作?

Answer 1:

若要从HWND转换(这仅仅是一个指针)IntPtr的,你只需要调用它的构造函数,你不需要gcnew,因为它是值类型。 所以这应该工作到HWND传递从原产地到管理:

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

这是你可以从托管代码调用,并在本机代码获取本地HWND的函数:

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


文章来源: Convert HWND to IntPtr (CLI)