Getting around Silverlight 2 beta 1 error 4002 while changing visibility of a control on mouse click event

by APIJunkie 27. May 2008 23:27

While working on  Bumble Beegger we came across a daunting problem that only seemed to happen under certain conditions.

Silverlight error message
ErrorCode: 4002
ErrorType: ManagedRuntimeError
Message: System.Exception: Error HRESULT E_FAIL has been returned from a call to a COM component.
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at System.Windows.DependencyObject.MethodEx(String methodName, CValue[] cvData)
at System.Windows.UIElement.ReleaseMouseCapture()
at System.Windows.Controls.Primitives.ButtonBase.ReleaseMouseCaptureInternal()
at System.Windows.Controls.Primitives.ButtonBase.OnLostFocus(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnLostFocus(Object sender, RoutedEventArgs e)
at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) 

After a few hours of debugging, experimenting and googling I came across a discussion on that shed some light on the problem.

As it turns out there is bug in Silverlight 2 beta 1 that can cause a crash when changing the visibility of a button control inside a mouse event handler.

The recommended workarounds around this problem were to change the size to 0,0 or change the opacity to 1.

Another option is to use the Canvas.ZIndexProperty and set it to a number that is smaller then your foreground elements.

The problem is that those does not always produce a similar enough effect in other elements.

If you still want to use visibility where possible, you can check the type of control and choose to modify visibility, size, opacity or Z Index according to the type.

Granted this is a horrible hack but it gets the job done until we can get our hands on beta 2...


// assume uiElement points to some valid UIElement

UIElement uiElement;

// check element type, if its not a button set visibility to collapsed else use ZIndex for a similar effect

if (uiElement.GetType() != typeof(Button)) 

   uiElement.Visibility = Visibility.Collapsed;


   ((Button)uiElement).SetValue(Canvas.ZIndexProperty, -1);


Silverlight | PRB | How To | Debug


5/27/2008 11:41:48 PM #


Trackback from

Getting around Silverlight 2 beta 1 error 4002 changing visibility

Comments are closed

About the author

Name of author

I was first wounded by x86 assembly, recovered and moved on to C. Following a long addiction to C++ and a short stint at rehab I decided to switch to a healthier addiction so I am now happily sniffing .NET and getting hooked on Silverlight.

I am mainly here to ramble about coding, various API’s, Junkies(me especially) and everything else that happens between coders and their significant other.

  James Bacon