Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hello,

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:

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


My C# code:

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


My CLI code:

C#
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

C#
m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);


if I change the CLI code to:

C++
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? Thanks

How can I make it work properly?
Thanks
Posted
Updated 14-Jan-13 22:28pm
v2
Comments
Michael Haephrati 7-Mar-13 16:14pm    
You need to pass a pointer to your handle, and not the handle itself

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900