Search code examples
c#winformsscreenshot

Screen Capture target area of the desktop


I'm trying to recreate a Winform application in C# that has the same functionality as the snipping tool windows provides. That is, allowing the user to drag a rectangle over the desktop and capture what ever is inside as an image.

At the moment I only have the ability to draw a rectangle with the mouse, and that's within the winform. Can anyone point me in the direction of how to do it so I can do it within the whole desktop?

My code for drawing the rectangle is as follows:

 Rectangle rect; 
    public Form1()
    {
        InitializeComponent();

        // set the cursor to be a + sign
        this.Cursor = System.Windows.Forms.Cursors.Cross;
        this.DoubleBuffered = true;
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        // e.X and e.Y are used to get the X and Y pos of the mouse
        rect = new Rectangle(e.X, e.Y, 0, 0);
        this.Invalidate();
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            // draw rectangle as mouse moves
            rect = new Rectangle(rect.Left,rect.Top, e.X - rect.Left, e.Y - rect.Top);
        }
        this.Invalidate();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Replace "Color.Red" with any color and repalce "2" with any size you like.
        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, rect);
        }
    }
}

I've been looking around online, but my searches haven't provided anything of use yet.

Any help would be greatly appreciated.


Solution

  • See:

    http://www.codeproject.com/Articles/485883/Create-your-own-Snipping-Tool

    And:

    http://www.codeproject.com/Articles/21913/TeboScreen-Basic-C-Screen-Capture-Application

    as references of Snipping tool creation.

    Hope this helps.