BaBu,
I do this exact thing when a user navigates away from my Silverlight app (or does a refresh). Follow the steps below to catch this event.
1.) Start by listening for the HTML page's "onbeforeunload" event, like so...
public void Application_Startup(object sender, StartupEventArgs e)
{
bool ok = HtmlPage.Window.AttachEvent("onbeforeunload", Application_BeforeExit);
ok = HtmlPage.Document.AttachEvent("onbeforeunload", Application_BeforeExit);
MainPage mainPage = new MainPage();
base.RootVisual = mainPage;
}
2.) Implement Application_BeforeExit() to setup and call an ASP.NET "PageMethod", like so...
private void Application_BeforeExit(object sender, HtmlEventArgs args)
{
string methodName = "ModelShutdown";
params object[] args = new Guid().ToString());;
try
{
ScriptObject pageMethods = (ScriptObject)HtmlPage.Window.GetProperty("PageMethods");
if (pageMethods == null)
throw new ArgumentException("Web page does not support PageMethods");
object[] pageMethodArgs = { new PageMethodEventHandler(Success), new PageMethodEventHandler(Failure), null/*userContext*/};
object[] combinedArgs = new object[args.Length + pageMethodArgs.Length];
args.CopyTo(combinedArgs, 0);
pageMethodArgs.CopyTo(combinedArgs, args.Length);
pageMethods.Invoke(methodName, combinedArgs);
}
catch (Exception ex)
{
//ex.Alert();
}
}
3.) Add the PageMethod to your page code behind (Index.aspx.cs), like so,
public partial class Index : Page
{
[WebMethod] // a PageMethod called from Silverlight
public static void ModelShutdown(string identifier)
{
System.Diagnostics.Debug.WriteLine("*** Signing Off: " + identifier);
}
}
4.) Allow PageMethods on your page (Indx.aspx), like so,
<asp:ScriptManager runat="server" EnablePageMethods="true" />
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
Good luck,
Jim McCurdy, YinYangMoney.com