我在播放电影控件上的视频时遇到问题,然后使用BringToFront()方法切换到家庭控件。视频仍在播放,声音仍在播放。
public partial class MoviesControl : UserControl
{
public MoviesControl()
{
InitializeComponent();
int width = 560;
int height = 315;
webBrowser1.Width = width + 2;
webBrowser1.Height = height + 2;
var embed = "<html><head>" +
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge,chrome=1\"/>" +
"</head><body scroll=\"no\" style=\"padding:0px;margin:0px;\">" +
"<iframe style=\"border: 1px solid #0000ff;\" width=\"{1}\" height=\"{2}\" src=\"{0}\"" +
"frameborder=\"0\" allow =\"autoplay; encrypted-media\" ></iframe>" +
"</body></html>";
string url = "https://www.youtube.com/embed/JvSZKB2WNKg?rel=0&showinfo=0";
webBrowser1.DocumentText = string.Format(embed, url, width, height);
}
}
最佳答案
YouTube Player API Reference for iframe Embeds允许您使用JavaScript代码控制播放器。
为了能够使用该脚本API,您应该通过在查询字符串中添加iframe
来加载enablejsapi=1
。
然后,要暂停视频,您正在寻找pauseVideo
命令。使用以下脚本可以暂停视频:
var i = document.getElementsByTagName("iframe")[0].contentWindow;
i.postMessage('{"event":"command","func":"pauseVideo","args":""}}', '*');
为了能够从Windows窗体调用它,请将其放在html代码中的函数中,然后使用broswer控件的
WebBrowserDocument.InvokeScript()
方法进行调用。示例
int w = 560;
int h = 315;
this.webBrowser1.Width = w + 2;
this.webBrowser1.Height = h + 2;
var embed = "<html><head>" +
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge,chrome=1\"/>" +
"<script>"+
"function stop() {{"+
"var i = document.getElementsByTagName(\"iframe\")[0].contentWindow;" +
"i.postMessage('{{\"event\":\"command\",\"func\":\"pauseVideo\",\"args\":\"\"}}', '*');" +
"}}</script>"+
"</head><body scroll=\"no\" style=\"padding:0px;margin:0px;\">" +
"<iframe style=\"border: 1px solid #fff;\" width=\"{1}\" height=\"{2}\" src=\"{0}\"" +
"allow =\"autoplay; encrypted-media\" ></iframe>" +
"</body></html>";
var url = "https://www.youtube.com/embed/JvSZKB2WNKg?enablejsapi=1&rel=0&showinfo=0";
webBrowser1.DocumentText = string.Format(embed, url, w, h);
然后,您可以随时随地暂停视频:
webBrowser1.Document.InvokeScript("stop", null);
关于c# - C#切换用户控件时暂停视频或停止Web浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053211/