【发布时间】:2015-06-23 03:38:30
【问题描述】:
我需要在 Windows 窗体控件中托管一个 Win32 窗口。我在使用 WPF 时遇到了同样的问题,我通过使用 HwndHost 控件解决了这个问题。
我遵循了这个教程:
Walkthrough: Hosting a Win32 Control in WPF
Windows 窗体中是否有任何等效控件?
我有一个Panel 及其Handle 属性,我将此句柄用作我的 Direct2D 渲染目标窗口的父级:
// Register the window class.
WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
// Redraws the entire window if a movement or size adjustment changes the height
// or the width of the client area.
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = Core::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(LONG_PTR);
wcex.hInstance = HINST_THISCOMPONENT;
wcex.hbrBackground = nullptr;
wcex.lpszMenuName = nullptr;
wcex.hCursor = LoadCursor(nullptr, IDI_APPLICATION);
wcex.lpszClassName = L"SVGCoreClassName";
RegisterClassEx(&wcex);
hwnd = CreateWindow(
L"SVGCoreClassName", // class name
L"", // window name
WS_CHILD | WS_VISIBLE, // style
CW_USEDEFAULT, // x
CW_USEDEFAULT, // y
CW_USEDEFAULT, // width
CW_USEDEFAULT, // height
parent, // parent window
nullptr, // window menu
HINST_THISCOMPONENT, // instance of the module to be associated with the window
this); // pointer passed to the WM_CREATE message
...
hr = d2dFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(hwnd, size, D2D1_PRESENT_OPTIONS_IMMEDIATELY),
&renderTarget);
如果我将 HwndHost 父句柄与 WPF 一起使用,则该代码有效。但如果我使用 System.Windows.Forms.Panel 句柄,它不会呈现任何内容。
【问题讨论】:
-
您可能对
NativeWindow感兴趣。 -
所有 Winforms 控件都已经是 Win32 窗口,因此“托管”没有多大意义。您需要更好地描述此窗口的性质。谁拥有它?你是如何创建它的?
-
@HansPassant 请看我的编辑。
-
这段代码有错误检查吗?你需要 if (hwnd == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();现在你就会知道为什么它不起作用了。
-
@HansPassant 我的 hwnd 是一个有效的指针,它不为空。我之前使用 WPF 进行的所有检查仍然保持不变,并且所有测试都通过了。
标签: c# c++ wpf winforms interop