Embedding YouTube in WPF WebBrowser control

By | 2010.06.27

Embedding YouTube into your C# WPF application can be done by wrapping embedded YouTube in a WebBrowser object (Internet Explorer). There are a couple of things you need to do to make it work.

Tested on Windows 7 Ultimate 64-bit in .Net 3.5 (VS 2010). Sample code can be found at the bottom.

  1. Add Mark of the Web to the HTML code: http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx
  2. Make sure you \r\n format your HTML-code. I read somewhere that some people had difficulties because the HTML was Mac-formatted.
  3. Make sure your app is set to execute as x86 (project properties) since it will use Flash which is not released as 64-bit yet. I spent quite some time debugging before it finally occurred to me that it was running as x64.

The Code I’m using:

Inside XAML:

<WebBrowser x:Name="webBrowser1" Margin="0,0,0,0" Height="240" Width="320"  />

In codebehind:

private Regex YouTubeURLIDRegex = new Regex(@"[\?&]v=(?<v>[^&]+)");
public void Display(string url)
    // Sample url: http://www.youtube.com/watch?v=p7aLl2ymkaE&playnext_from=TL&videos=afsfl56bccg&feature=sub
    Match m = YouTubeURLIDRegex.Match(url);
    String id = m.Groups["v"].Value;
    string page =
    "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" >\r\n"
    + @"<!-- saved from url=(0022)http://www.youtube.com -->" + "\r\n"
    + "<html><body scroll=\"no\" leftmargin=\"0px\" topmargin=\"0px\" marginwidth=\"0px\" marginheight=\"0px\" >" + "\r\n"
        + GetYouTubeScript(id)
        + "</body></html>\r\n";
private string GetYouTubeScript(string id)
    string scr = @"<object width='320' height='240'> "+"\r\n";
    scr = scr + @"<param name='movie' value='http://www.youtube.com/v/" + id + "'></param> " + "\r\n";
    scr = scr + @"<param name='allowFullScreen' value='true'></param> " + "\r\n";
    scr = scr + @"<param name='allowscriptaccess' value='always'></param> " + "\r\n";
    scr = scr + @"<embed src='http://www.youtube.com/v/" + id + "' ";
    scr = scr + @"type='application/x-shockwave-flash' allowscriptaccess='always' ";
    scr = scr + @"allowfullscreen='true' width='320' height='240'> " + "\r\n";
    scr = scr + @"</embed></object>" + "\r\n";
    return scr;

Result when embedded into RTF control:

Leave a Reply