Thursday, December 16, 2010

Capturing The Desktop using C#

In previous posts we have learnt how to use pictures in Oracle vis-a-vis Java, in MySQL via PHP, and MS SQL Server via ASP.NET, Windows Forms Applications, and WCF. In this post I will show how to capture the Desktop as an Image and display it in a Picture Box in a Windows Application. To do this we need to access the Windows API. I have developed a static class DesktopImageCapturer for this purpose. It captures the Desktop and returns it as a System.Drawing.Image object.
Here is the class 


DesktopImageCapturer.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopCapturer
{
    public static class DesktopImageCapturer
    {
        [DllImport("GDI32.dll")]
        private  static extern bool BitBlt(int hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, int hdcSrc, int nXSrc, int nYSrc, int dwRop);
        [DllImport("GDI32.dll")]
        private static extern int CreateCompatibleBitmap(int hdc, int nWidth, int nHeight);
        [DllImport("GDI32.dll")]
        private static extern int CreateCompatibleDC(int hdc);
        [DllImport("GDI32.dll")]
        private static extern bool DeleteDC(int hdc);
        [DllImport("GDI32.dll")]
        private static extern bool DeleteObject(int hObject);
        [DllImport("GDI32.dll")]
        private static extern int GetDeviceCaps(int hdc, int nIndex);
        [DllImport("GDI32.dll")]
        private static extern int SelectObject(int hdc, int hgdiobj);
        [DllImport("User32.dll")]
        private static extern int GetDesktopWindow();
        [DllImport("User32.dll")]
        private static extern int GetWindowDC(int hWnd);
        [DllImport("User32.dll")]
        private static extern int ReleaseDC(int hWnd, int hDC);
      
            public static  Image   GetTheDesktop()
            {
              int hdcSrc = GetWindowDC(GetDesktopWindow());
              int  hdcDest = CreateCompatibleDC(hdcSrc);
              int  hBitmap = CreateCompatibleBitmap(hdcSrc, GetDeviceCaps(hdcSrc, 8), GetDeviceCaps(hdcSrc, 10));
              SelectObject(hdcDest, hBitmap);
              BitBlt(hdcDest, 0, 0, GetDeviceCaps(hdcSrc, 8),
              GetDeviceCaps(hdcSrc, 10), hdcSrc, 0, 0, 0x00CC0020);
              Image img = Image.FromHbitmap(new IntPtr(hBitmap));
              ReleaseDC(GetDesktopWindow(), hdcSrc);
              DeleteDC(hdcDest);
              DeleteObject(hBitmap);
              return img;
            }
         
        }
    }

Here is the Windows Form
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DesktopCapturer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
           
        picDesktop.Image =    DesktopImageCapturer.GetTheDesktop ();
       
        }
    }
}

Form1.Designer.cs

namespace DesktopCapturer
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.picDesktop = new System.Windows.Forms.PictureBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.picDesktop)).BeginInit();
            this.SuspendLayout();
            //
            // picDesktop
            //
            this.picDesktop.Dock = System.Windows.Forms.DockStyle.Fill;
            this.picDesktop.Location = new System.Drawing.Point(0, 0);
            this.picDesktop.Name = "picDesktop";
            this.picDesktop.Size = new System.Drawing.Size(782, 464);
            this.picDesktop.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picDesktop.TabIndex = 0;
            this.picDesktop.TabStop = false;
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 5000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(782, 464);
            this.Controls.Add(this.picDesktop);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox picDesktop;
        private System.Windows.Forms.Timer timer1;
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace DesktopCapturer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

 
In a subsequent Post I'll show how we can capture the Screen via a Java Application, and also how to send this Image through a WCF Service. Maybe some you can refer the old WCF app and do it yourself.

1 comment:

  1. Your Code is Awesome.I have To Save those captured screen simultaniously in image forms by enebling time span in those span i have to take certain screen shots and save them

    ReplyDelete