Detecting a Client's screen resolution in ASP.NET
by Serge Baranovsky
12/8/2002
Article source code: screenresolution.zip
While there is no "native" to determine client bowser screen resolution in .NET Framework your ASP.NET application still can retrieve this information using little client-side JavaScript trick.
Into your page (default.aspx in our case) we want to add code that will redirect to the screen detection page if it has never been done yet in the current session - Session["ScreenResolution"] is null
default.aspx:
<script runat="server" language="C#">
public void Page_Load(Object sender, EventArgs e){
if (Session["ScreenResolution"] == null) {
// Session variable is not set
// Redirect to the screen resolution detection script
Response.Redirect("detectscreen.aspx");
} else {
// Session variable is set
// Display it on the page
screenresolution.Text = Session["ScreenResolution"].ToString();
}
}
</script>
<HTML>
<BODY>
User screen resolution: <asp:label id="screenresolution" runat="server">undetected</asp:label>
</BODY>
<HTML>
The screen resolution detection script (detectscreen.aspx) determines the client screen height, width, color depth and redirects back to the default.aspx page
public void Page_Load(Object sender, EventArgs e){
if (Request.QueryString["action"] != null) {
// store the screen resolution in Session["ScreenResolution"]
// and redirect back to default.aspx
Session["ScreenResolution"] = Request.QueryString["res"].ToString();
Response.Redirect("default.aspx");
}
}
// JavaScript code below will determine the user screen resolution
// and redirect to itself with action=set QueryString parameter
</script>
<HTML><BODY>
<script language="javascript">
res = "&res="+screen.width+"x"+screen.height+"&d="+screen.colorDepth
top.location.href="detectscreen.aspx?action=set"+res
</script>
</BODY></HTML>
Here is yet another script that will be useful while testing the two above - it resets the Session["ScreenResolution"] variable to null
reset.aspx:<script runat="server" language="C#">
public void Page_Load(Object sender, EventArgs e){
Session["ScreenResolution"] = null;
}
</script>
Session["ScreenResolution"] has been reset to <i>null</i>