简体   繁体   English

将HWND转换为IntPtr(CLI)

[英]Convert HWND to IntPtr (CLI)

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. 我的C ++ MFC代码中有一个HWND,我想将此HWND传递给C#控件并将其作为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...) (我认为使用CLI指针是错误的,因为我收到一个错误,它无法从System :: IntPtr ^转换为System :: IntPtr。但是我不知道如何使它们正常工作。 ..)

My C++ MFC code: 我的C ++ MFC代码:

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

My C# code: 我的C#代码:

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

My CLI code: 我的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);
    }

Error (cannot convert from IntPtr^ to IntPtr) currently occurs on m_pManagedData->CSharpControl->UpdateHandle(managedhWnd); 当前在m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);上发生错误(无法从IntPtr ^转换为IntPtr m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);

if I change the CLI code to: 如果我将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);
    }

So in this case the value gotten in C# is 0. 因此,在这种情况下,在C#中获得的值为0。

How can I make it work properly? 如何使它正常工作?

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. 要将HWND(仅是指针)转换为IntPtr,您只需调用它的构造函数,并且不需要gcnew,因为它是一种值类型。 So this should work to pass a HWND from native to managed: 因此,这应该可以将HWND从本地传递到托管:

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: 这是一个您可以从托管代码中调用并从本地代码中获取本地HWND的函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM