你可以把 WinForms 控件嵌入到 WPF 里,也可以反过来把 WPF 控件嵌入到 Windows Forms。
WPF 使用 WindowsFormsHost 来承载 WinForms 控件。
例如,把 WinForms 的“字幕渲染器 / 视频播放器控件”嵌入 WPF:
✔ 在 WinForms 内使用 libass / mpv / FFmpeg 播放器
✔ 然后把这个 WinForms 控件通过 WindowsFormsHost 放到 WPF
实现在 WPF 中支持复杂字幕渲染(ASS)。
你可以放任何 WinForms 控件:
✔ WinForms UserControl
✔ Panel
✔ DataGridView
✔ PictureBox
✔ WebBrowser
✔ MediaPlayer
✔ 你自己做的 WinForms 控件
强化兼容性:WinForms 控件会被当作一个 AIR 层(Hwnd),WPF 无法覆盖它(反之亦然)。
在你的 WPF 项目里添加引用:
```xml
下面加载一个panel,(mpvPanel 是 WinForms Panel)
```xml
<WindowsFormsHost Name="winFormsHost">
<panel:MPVPanel x:Name="mpvPanel"/>
</WindowsFormsHost>
然后C# 中初始化 mpv
var mpv = new MpvPlayer(mpvPanel.Handle);
mpv.LoadFile("video.mp4");
mpv.Command("sub-add", "subtitle.ass");
var mpv = new MpvPlayer();
mpv.Initialize(videoHost.Handle); // WindowsFormsHost.Handle
mpv.LoadFile(videoFilePath);
mpv.LoadSubtitles(subtitleFilePath);
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using SubtitleEditNamespace; // DLL 里的命名空间
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var host = new WindowsFormsHost();
var winformButton = new Button();
winformButton.Text = "WinForms Button";
host.Child = winformButton;
this.Content = host;
var subtitleControl = new SubtitleEditControl(); // 你的控件类
winFormsHost.Child = subtitleControl;
}
}
ElementHost
混合使用时:
如:
需要手动设置字体、颜色等。