Async's blog - 渲染
type: channel
link: https://blog.async.website/index.php/tag/%E6%B8%B2%E6%9F%93/
items: C# LibVLCSharp将VLC窗口渲染至当前窗口的两种方式

C# LibVLCSharp将VLC窗口渲染至当前窗口的两种方式
type: item
date: 2025-05-20T02:02:00+00:00
description: 在添加了LibVLCSharp和LibVLCSharp.Platforms.Windows的Nuget包后，新建media绑定至XAML页面的VideoView的MediaPlayer，启动Play事件，VLC会弹出一个单独的Foreground窗口来进行输出，尝试了两种方式将MediaPlayer约束近当前窗口。1.句柄方法0X00.引用using LibVLCSharp.Platforms.Windows; using LibVLCSharp.Shared;0X01.NativeMethodspublic static class NativeMethods { [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetActiveWindow(); [DllImport("user32.dll", SetLastError = true)] public static extern bool IsWindow(IntPtr hWnd); } //通过P/Invoke调用Windows API0X02.获取Foreground窗口句柄并渲染VLCprivate MediaPlayer mediaPlayer; private IntPtr hwnd; private LibVLC libVLC; mediaPlayer ??= new MediaPlayer(libVLC); mediaPlayer. Media = new Media(libVLC, new System.Uri("your video uri here")); mediaPlayer.Hwnd = hwnd; if (!mediaPlayer.IsPlaying) mediaPlayer.Play();2.SwapChain方法0X00.引用using LibVLCSharp.Platforms.Windows; using LibVLCSharp.Shared;0X01.VideoView Initialized事件private MediaPlayer mediaPlayer; private LibVLC libVLC; private string[] swapChain; private void videoView_Initialized(object sender, InitializedEventArgs e) { swapChain = e.SwapChainOptions; libVLC = new LibVLC(swapChain); }0X02.PageLoaded事件private void Page_Loaded(object sender, RoutedEventArgs e) { mediaPlayer ??= new MediaPlayer(libVLC); mediaPlayer. Media = new Media(libVLC, new System.Uri("your video uri here")); videoView.MediaPlayer=mediaPlayer; if (!videoView.MediaPlayer.IsPlaying) videoView.MediaPlayer.Play(); }