C# Pause video or stop Web browser when switching UserControls

混江龙づ霸主 提交于 2019-12-11 08:45:08

问题


I have a problem, when i'm playing a video on e.g movies control and then switch to home control with bringToFront() method. The video is still playing, atleast the sound is still doing it.

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&amp;showinfo=0";
        webBrowser1.DocumentText = string.Format(embed, url, width, height);
    }
}

回答1:


YouTube Player API Reference for iframe Embeds allows you to control the player using javascript code. To be able to use that script API, you should load the iframe by adding enablejsapi=1 to query string.

Then for pausing a video, you are looking for pauseVideo command. Using the following script you can pause the video:

var i = document.getElementsByTagName("iframe")[0].contentWindow;
i.postMessage('{"event":"command","func":"pauseVideo","args":""}}', '*');

To be able to call it from windows forms, put it in a function in your html code, then call it using WebBrowserDocument.InvokeScript() method of the broswer control.

Example

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&amp;showinfo=0";
webBrowser1.DocumentText = string.Format(embed, url, w, h);

Then you can pause the video simply whenever you want:

webBrowser1.Document.InvokeScript("stop", null);


来源:https://stackoverflow.com/questions/49053211/c-sharp-pause-video-or-stop-web-browser-when-switching-usercontrols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!