我的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);
}m_pManagedData->CSharpControl->UpdateHandle(managedhWnd);上当前出现错误(无法从IntPtr^转换为IntPtr)
如果我将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。
我怎样才能让它正常工作?
发布于 2013-01-15 17:28:06
要将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();
//...
}https://stackoverflow.com/questions/14334261
复制相似问题