问题描述
我的 C++ MFC 代码中有一个 HWND,我想将此 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 指针有问题,因为我收到一个错误,它无法从 System::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# 代码:
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);
如果我将 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!