将HWND转换为IntPtr(CLI)

12

我在我的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);
    }

目前发生了一个错误 (无法将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。

我该如何使其正常工作?


你能发一份最小的代码来重现错误吗?同时告诉我错误具体出现在哪里? - stijn
1个回答

22

要将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();
  //...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接