转换为HWND的IntPtr(CLI) [英] Convert HWND to IntPtr (CLI)
问题描述
我有一个HWND在我的C ++ MFC代码,我想这HWND传递给一个C#的控制,并把它作为IntPtr的。
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.
什么是错误的,我代码,我怎么能正确地做到这一点?
(我认为这是一些与错误使用CLI指针,因为我得到一个错误,它不能从系统转换:: IntPtr的^到System :: 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...)
我的C ++ MFC代码:
My C++ MFC code:
HWND myHandle= this->GetSafeHwnd();
m_CLIDialog->UpdateHandle(myHandle);
我的C#代码:
My C# code:
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代码:
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);
}
因此,在这种情况下,在C#中得到的值是0。
So in this case the value gotten in C# is 0.
我怎样才能使其正常工作?
How can I make it work properly?
推荐答案
要从HWND转换(其中只是一个指针)IntPtr的,你只需要调用它的构造函数,你不需要gcnew,因为它是值类型。
所以这应该努力从本地一个HWND传递给管理:
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 );
}
这是你可以从托管代码调用并获得本地HWND的函数从本机代码:
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();
//...
}
这篇关于转换为HWND的IntPtr(CLI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!