Quickly resize the Silverlight plugin to zero pixels in size

24 August 2008

When I was a test developer on the team that built the HTML DOM bridge feature for Silverlight 2, I often found myself needing to create a tiny, quick application to reproduce an issue. That meant quickly creating projects that used the dynamic test page, and without modifying the TestPage.html.

The goal was to resize or hide the Silverlight plugin and its hosting element. Here's what I've been using as a code snippet that drops the ZeroPixelPlugin in the System.Windows.Browser namespace.

One fine function call (Page.xaml.cs):

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        ZeroPixelPlugin.HideSilverlightPlugin();

        // Throw a button up there on the page that doesn't do anything
        HtmlElement button = HtmlPage.Document.CreateElement("button");
        button.SetAttribute("value", "Hello world!");
        HtmlPage.Document.Body.AppendChild(button);
    }

And here's the utility, in Visual Basic:

Imports System.Windows.Browser

Namespace System.Windows.Browser
    Public Class ZeroPixelPlugin
        ''' <summary>
        ''' Resizes the Silverlight plugin and its host element to be zero pixels 
        ''' in width and height. Only really useful for HTML
        ''' </summary>
        ''' <remarks></remarks>
        Public Shared Sub HideSilverlightPlugin()
            Dim plugin As HtmlElement = HtmlPage.Plugin
            Dim host As HtmlElement = plugin.Parent
            plugin.SetStyleAttribute("width", "0")
            plugin.SetStyleAttribute("height", "0")
            host.SetStyleAttribute("width", "0")
            host.SetStyleAttribute("height", "0")
        End Sub
    End Class
End Namespace

And in C#:

// This code is useful for Html DOM bridge testing. It is placed in this 
// namespace since it sort of assumes you're only using that feature and 
// not the rich Silverlight presentation framework.

namespace System.Windows.Browser
{
    public static class ZeroPixelPlugin
    {
        /// <summary>
        /// Resizes the Silverlight plugin and its host element to be zero pixels 
        /// in width and height. Only really useful for HTML
        /// </summary>
        public static void HideSilverlightPlugin()
        {
            HtmlElement plugin = HtmlPage.Plugin;
            HtmlElement host = plugin.Parent;
            plugin.SetStyleAttribute("width", "0");
            plugin.SetStyleAttribute("height", "0");
            host.SetStyleAttribute("width", "0");
            host.SetStyleAttribute("height", "0");
        }
    }
}

Just thought it was somewhat interesting for anybody doing work outside of the rich Silverlight presentation framework.

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus