You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm中如何让WebViewer内YouTube视频铺满控件?附浏览器跳转问题

解决方案

问题1:让视频自动铺满WebBrowser控件

你当前的HTML中,<html>和<body>标签默认带有边距,导致视频无法完全填充控件。需要修改HTML代码,给根元素设置全屏样式,同时确保iframe的尺寸完全适配容器:

string url = "https://www.youtube.com/watch?v=5aCbWqKl-wU";
string html = @"<html>
<head>
    <meta content='IE=Edge' http-equiv='X-UA-Compatible'/>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <iframe id='video' src='https://www.youtube.com/embed/{0}?rel=0' 
            style='width: 100%; height: 100%; border: none; display: block;' 
            allowfullscreen></iframe>
</body></html>";
webBrowser1.DocumentText = string.Format(html, url.Split('=')[1]);

另外确保WebBrowser控件的以下属性设置正确:

  • Anchor设为Top, Bottom, Left, Right(你已完成设置)
  • ScrollBarsEnabled设为false,避免出现滚动条干扰填充效果

问题2:点击YouTube按钮打开默认浏览器

WebBrowser控件默认使用IE内核处理导航,需要拦截导航事件,手动调用系统默认浏览器打开外部链接:

  1. 给WebBrowser控件添加Navigating事件处理程序:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    // 判断是否为YouTube的外部跳转链接
    if (e.Url.Host.Contains("youtube.com") && !e.Url.AbsolutePath.StartsWith("/embed/"))
    {
        // 取消WebBrowser的默认导航行为
        e.Cancel = true;
        // 调用系统默认浏览器打开链接
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Url.ToString()) 
        { 
            UseShellExecute = true 
        });
    }
}
  1. 在窗体构造函数中绑定事件(或通过设计器直接绑定):
public YourFormName()
{
    InitializeComponent();
    webBrowser1.Navigating += webBrowser1_Navigating;
}

注:UseShellExecute = true是核心配置,它会让系统调用默认应用打开指定URL。

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:20:39