Saturday, December 18, 2010

Drawing on the Desktop using C#

In this application we shall learn how to draw over the desktop. To do this we shall make use of the following windows api functions.
       [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 SelectObject(int hdc, int hgdiobj);
        [DllImport("User32.dll")]
        private static extern int GetDesktopWindow();
        [DllImport("User32.dll")]
        private static extern int GetWindowDC(int hWnd);
        [DllImport("GDI32.dll")]
        private static extern int LineTo(int hdc, int x, int y);
        [DllImport("GDI32.dll")]
        private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
        [DllImport("GDI32.dll")]
        private static extern int CreatePen(int penstyle, int width, int color);


Using these functions I have developed a class called DesktopDrawing
which contains a static method public static  void    DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
The parameters are self explanatory.
The method makes use of the following Windows API functions:-
1) GetDesktopWindow gets a handle to the Desktop.
2) GetWindowDC gets the Device Context to a window given it's handle.
3) CreatePen Creates a Pen for drawing, given a DrawMode, width and Color.
4) SelectObject Selects a Pen for drawing into a DeviceContext.
5) MoveToEx Moves the Current Point of a DeviceContext to a specified X,Y Position. It also returns the new Point by a reference Parameter.
6) LineTo Draws a Line from the Current Point in a DeviceContext to a given X,Y Position .
7) DeleteDC Deletes a DeviceContext and releases the resources used.
8) DeleteObject Deletes an Object and releases the used resources.

The Application
DesktopDrawing.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopPainter
{
    public static class DesktopDrawing
    {
       [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 SelectObject(int hdc, int hgdiobj);
        [DllImport("User32.dll")]
        private static extern int GetDesktopWindow();
        [DllImport("User32.dll")]
        private static extern int GetWindowDC(int hWnd);
        [DllImport("GDI32.dll")]
        private static extern int LineTo(int hdc, int x, int y);
        [DllImport("GDI32.dll")]
        private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
        [DllImport("GDI32.dll")]
        private static extern int CreatePen(int penstyle, int width, int color);


            public static  void    DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
            {
                Point p=new Point ();
              int hdcSrc = GetWindowDC(GetDesktopWindow());
              int newcolor  =System.Drawing .ColorTranslator.ToWin32 ( clr);
               
              int newpen=CreatePen(0,width , newcolor);
              SelectObject(hdcSrc,newpen );
              MoveToEx(hdcSrc, x1, y1, ref p);
              LineTo(hdcSrc,x2,y2);
              DeleteDC(hdcSrc);
              DeleteObject(newpen);
             
            }
         
        }
    }
Program.cs

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

namespace DesktopPainter
{
    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());
        }
    }
}

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 DesktopPainter
{
    public partial class Form1 : Form
    {
        bool IsColorDialogOpened = false;
        int px = 0, py = 0;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!chkDraw.Checked || IsColorDialogOpened )
                return;
            int x = Cursor.Position.X;
            int y = Cursor.Position.Y;
            DesktopDrawing.DrawALine(px, py, x, y,50, lblDrawingColor.BackColor );
            px = x;
            py = y;
       
        }

        private void lblDrawingColor_Click(object sender, EventArgs e)
        {
            IsColorDialogOpened = true;
            cld.Color = lblDrawingColor.BackColor;
            cld.AllowFullOpen = true;
            cld.ShowDialog(this);
            lblDrawingColor.BackColor = cld.Color;
            IsColorDialogOpened = false;
           
        }

        private void chkDraw_CheckedChanged(object sender, EventArgs e)
        {
            px = Cursor.Position.X;
            py = Cursor.Position.Y;
        }
    }
}



Form1.Designer.cs

namespace DesktopPainter
{
    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);
            this.cld = new System.Windows.Forms.ColorDialog();
            this.lblDrawingColor = new System.Windows.Forms.Button();
            this.chkDraw = new System.Windows.Forms.CheckBox();
            ((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 = 200;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // cld
            //
            this.cld.Color = System.Drawing.Color.Red;
            //
            // lblDrawingColor
            //
            this.lblDrawingColor.BackColor = System.Drawing.Color.Red;
            this.lblDrawingColor.Location = new System.Drawing.Point(122, 71);
            this.lblDrawingColor.Name = "lblDrawingColor";
            this.lblDrawingColor.Size = new System.Drawing.Size(156, 33);
            this.lblDrawingColor.TabIndex = 1;
            this.lblDrawingColor.Text = "&Drawing Color";
            this.lblDrawingColor.UseVisualStyleBackColor = false;
            this.lblDrawingColor.Click += new System.EventHandler(this.lblDrawingColor_Click);
            //
            // chkDraw
            //
            this.chkDraw.AutoSize = true;
            this.chkDraw.Location = new System.Drawing.Point(357, 86);
            this.chkDraw.Name = "chkDraw";
            this.chkDraw.Size = new System.Drawing.Size(79, 17);
            this.chkDraw.TabIndex = 2;
            this.chkDraw.Text = "Draw &Lines";
            this.chkDraw.UseVisualStyleBackColor = true;
            this.chkDraw.CheckedChanged += new System.EventHandler(this.chkDraw_CheckedChanged);
            //
            // 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.chkDraw);
            this.Controls.Add(this.lblDrawingColor);
            this.Controls.Add(this.picDesktop);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.PictureBox picDesktop;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.ColorDialog cld;
        private System.Windows.Forms.Button lblDrawingColor;
        private System.Windows.Forms.CheckBox chkDraw;
    }
}




I have deliberately kept it a bit rough round the edges while still providing the basic requirements. Enter your E Mail in the comments if you want a zip of the Application.

8 comments: