a blog for those who code

Sunday 7 September 2014

Print Screen in Asp Net Web Application

In this post we will show you how to take Full Screen Shot using Asp.Net web application.

In this application on clicking "Ctrl + Q" you will get the images of the screens and stored in a folder.
If you are working on multiple monitors (say 2), then the screen of both the monitor (different images) is stored in that folder.

At first you have to add the reference of System.Windows.Form. Why because, you need Screen class of this namespace. This Class is used to capture the screen of your monitor.
You need to add jQuery, Screenshots folder to store images as shown below.
Add a new page (PrintPage.aspx) and add the below code into it

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PrintPage.aspx.cs" Inherits="PrintScreen.PrintPage" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Capture Screen</title>
</head>
<body>
    <%--Adding jQuery Script--%>
    <script src="Script/jquery-2.1.1.min.js" type="text/javascript" ></script>

    <script>
        $(function () {
            $(document).on('keyup keydown keypress', function (event) {
                console.log(event);
                if (event.keyCode == 81 && event.ctrlKey) {
                    PageMethods.ScreenShot();
                }
            });
        });
    </script>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
        Capture Screen on the fly using Shortcut Ctrl + Q
    </div>
    </form>
</body>
</html>

Add the below code into code behind file (PrintPage.aspx.cs)

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Windows.Forms;

namespace PrintScreen
{
  public partial class PrintPage : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {}
    [WebMethod]
    public static void ScreenShot()
    {
      foreach (Screen screen in Screen.AllScreens)
      {
         Bitmap bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height, PixelFormat.Format32bppArgb);

         using (Graphics graphics = Graphics.FromImage(bitmap))
         {
             graphics.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, screen.Bounds.Size, CopyPixelOperation.SourceCopy);
         }

        bitmap.Save( HttpContext.Current.Server.MapPath ("/Screenshots/ " + screen.DeviceName.ToLower() + ".jpg"));
            }
        }
    }
}

You can download the demo project here.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment