Convert HWND to IntPtr (CLI)

隐身守侯 提交于 2019-11-30 02:10:31

问题


I have a HWND in my C++ MFC code, and I want to pass this HWND to a C# control and get it as IntPtr.

What Is wrong in my code, and how can I do it correctly? (I think it's something with wrong using of the CLI pointers, because I get an error that it cannot convert from System::IntPtr^ to System::IntPtr. But I don't know how exactly to make it all to work properly...)

My C++ MFC code:

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

My C# code:

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

My CLI code:

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);
    }

Error (cannot convert from IntPtr^ to IntPtr) currently occurs on m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);

if I change the CLI code to:

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);
    }

So in this case the value gotten in C# is 0.

How can I make it work properly?


回答1:


To convert from HWND (which is just a pointer) to IntPtr you just have to invoke it's constructor, and you do not need gcnew as it's a value type. So this should work to pass a HWND from native to managed:

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

And this is a function you can invoke from managed code and get a native HWND from in native code:

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


来源:https://stackoverflow.com/questions/14334261/convert-hwnd-to-intptr-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!