我需要在 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
句柄,它不会呈现任何内容。
最佳答案
您必须在 WPF 中执行的创建有效 D2D1 目标窗口的操作在 Winforms 中是不必要的。在 WPF 中这是必要的,因为控件本身不是窗口,并且没有 Handle 属性,而 CreateHwndRenderTarget() 需要该属性。
在 Winforms 中 Panel 类已经是一个非常好的渲染目标,你可以使用它的 Handle 属性来告诉 D2D1 在哪里渲染。你只需要告诉它停止绘画本身。向您的项目添加一个新类并粘贴此代码:
using System;
using System.Windows.Forms;
class D2D1RenderTarget : Control {
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!this.DesignMode) {
this.SetStyle(ControlStyles.UserPaint, false);
// Initialize D2D1 here, use this.Handle
//...
}
}
}
编译。将新控件拖放到表单上,替换现有面板。
关于c# - 适用于 Windows 窗体的 HwndHost - Win32/WinForm 互操作性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679667/