Click here to Skip to main content
15,861,168 members
Articles / Desktop Programming / Windows Forms

OneNote Style Screen Capture Utility - with Preview and Auto Save Options

Rate me:
Please Sign up or sign in to vote.
4.45/5 (11 votes)
2 Dec 2011CPOL3 min read 44.9K   2.6K   43   17
A utility to capture and crop the screen just like OneNote (Office 2010)
Preview_Media_updated.png

Introduction

Most of you who work with 'OneNote' might have experienced the screen capturing future added to the Office 2010 package. Unlike the conventional print screen feature, this facility provides an option to freeze the screen and crop the image on the active desktop.

I found this really helpful when creating Office 2010 like Ribbon for our application to get the minute details of the Office 2010 visuals. Here is a utility that gives you the same experience to capture the screen and crop.

Background

Here is how it works:

  • The main app runs in the background and listens to the HOT KEY (Win Key + S) to capture the screen.
  • As soon as the Main app receives the WM_HOTKEY message, the main app captures the desktop and passes it onto an adorner window.
  • The adorner window presents the opaque image on top of all the other windows for you to crop with the mouse.
  • The cropped image is then made to the clipboard and that's it!

Using the Code

Listening to the HOTKEY

HOTKEY is the option the users can bring this application alive. To make this work, this application user native pinvokes to register and unregister HOTKEY.

RegisterHotKey

This function requires a handle to the calling window to which the WM_HOTKEY message will be posted when the key combination is pressed, and an ID as a reference to the HOTKEY, (there exists a range for this value, take a look at the Remarks section of the documentation) and a modifier value specifying the modifier key with which the key parameter is to be registered.

Win key along with 'S' is used as a HOTKEY for this application and the code for function is as in the following code block.

C#
// Definition of Native Method.
[DllImport("user32.dll", SetLastError = true)]
private static extern int RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);

//Param : A handle to the window, an id for the hotkey ,id of modifer key and the key.
RegisterHotKey(this.Handle, hotKeyId,/*MOD_WIN*/0x0008, Keys.S);

UnregisterHotKey

Un-registering a HOTKEY is relatively simple, it requires a handle to the calling window and the id used while registering the HOTKEY.

C#
// A handle to the calling window and the id used while registering.
UnregisterHotKey(this.Handle, hotKeyId);

The next big thing is to get the bitmap of the desktop window, there exists a native function GetDesktopWindow to get the desktop handle with which you can copy the graphics context to a bitmap. Alternatively, this can be done with the Graphics.CopyFromScreen method as follows later this bitmap is projected as a opaque image, providing a frozen desktop appearance.

C#
public static Bitmap GenerateScreenBitmap()
{
    Rectangle scrBounds = Screen.PrimaryScreen.Bounds;
    Bitmap bmp = new Bitmap(scrBounds.Width, scrBounds.Height);
    Graphics g = Graphics.FromImage(bmp);

    g.CopyFromScreen(Point.Empty, Point.Empty, 
	scrBounds.Size, CopyPixelOperation.SourceCopy);

    bitmapCache = bmp;

    return bmp;
}

The resultant bitmap image is set as the background of an adorner window and the window is shown, this adorner window overrides its OnPaint method to fill the region with a alpha blend to give an opaque look. he adorner processes the mouse events to determine the cropped region. dragStart dragStop determines the upper left and bottom right points of the cropped image.

C#
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Region clip = e.Graphics.Clip;

    if (mousePressed && dragStart!= Point.Empty && dragStart != dragStop)
    {
        Rectangle rect = Rectangle.FromLTRB
		(dragStart.X, dragStart.Y, dragStop.X, dragStop.Y);

        using (Pen pen = new Pen(Color.Black))
        {
            e.Graphics.DrawRectangle(pen, Rectangle.Inflate(rect,-1,-1));
        }

        // Excludes the cropped region and paints the remaining surface.
        e.Graphics.SetClip(rect, CombineMode.Exclude);
    }

    using (Brush brush = new SolidBrush(Color.FromArgb(210,Color.WhiteSmoke)))
    {
        e.Graphics.FillRectangle(brush, this.ClientRectangle);
    }

    e.Graphics.SetClip(clip, CombineMode.Replace);
}

The adorner will be closed when a mouse button is pressed or when a key is pressed, and the dragStart and dragStop points are passed to the main window, which copies the target cropped image to the clipboard.

C#
Rectangle rect = Rectangle.FromLTRB(adornerWindow.DragStart.X, 
	adornerWindow.DragStart.Y, adornerWindow.DragStop.X, adornerWindow.DragStop.Y);

Bitmap result = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(result);

g.DrawImage(bitmapCache,new Rectangle(Point.Empty,result.Size), rect, GraphicsUnit.Pixel);

Clipboard.SetImage(result);

And that's it, the image is now copied to the clipboard, you can paste it wherever required.

Points of Interest

This utility provides an option to start this application when windows starts and here is how you can make it, it just requires to place the application start up path and application name in a registry key at the following location:

C#
string RegKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

RegistryKey startUpKey = Registry.CurrentUser.OpenSubKey(RegKey, true);
                
ToolStripMenuItem menuItem = (sender as ToolStripMenuItem);
menuItem.Checked = !menuItem.Checked;

if (menuItem.Checked)
    startUpKey.SetValue(APP_NAME, Application.ExecutablePath);
else
    startUpKey.DeleteValue(APP_NAME, false);

Hope this helps in your day to day work. Leave your valuable comments and suggestions. Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I code, learn, read and listen.

Comments and Discussions

 
QuestionAutoSaving the File ? Pin
Ferozshaikh1-Dec-11 19:15
Ferozshaikh1-Dec-11 19:15 
AnswerRe: AutoSaving the File ? Pin
VallarasuS1-Dec-11 19:20
VallarasuS1-Dec-11 19:20 
GeneralRe: AutoSaving the File ? Pin
Ferozshaikh1-Dec-11 19:26
Ferozshaikh1-Dec-11 19:26 
GeneralRe: AutoSaving the File ? Pin
VallarasuS1-Dec-11 20:17
VallarasuS1-Dec-11 20:17 
GeneralRe: AutoSaving the File ? Pin
Ferozshaikh3-Dec-11 2:21
Ferozshaikh3-Dec-11 2:21 
AnswerRe: AutoSaving the File ? Pin
VallarasuS1-Dec-11 19:22
VallarasuS1-Dec-11 19:22 
QuestionNice utility Pin
GuyThiebaut3-Jul-11 1:06
professionalGuyThiebaut3-Jul-11 1:06 
AnswerRe: Nice utility Pin
VallarasuS3-Jul-11 1:17
VallarasuS3-Jul-11 1:17 
GeneralRe: Nice utility Pin
GuyThiebaut4-Jul-11 1:52
professionalGuyThiebaut4-Jul-11 1:52 
QuestionInteresting... Pin
dave.dolan2-Jul-11 19:05
dave.dolan2-Jul-11 19:05 
AnswerRe: Interesting... Pin
VallarasuS2-Jul-11 19:27
VallarasuS2-Jul-11 19:27 
OMG | :OMG: You were right! Guess it is not available in XP and earlier version!! Unsure | :~ Thanks though! (ting)!!
GeneralMy vote of 4 Pin
jayantbramhankar2-Jul-11 18:40
jayantbramhankar2-Jul-11 18:40 
Questionproposal [modified] Pin
MarkDoubson2-Jul-11 9:12
MarkDoubson2-Jul-11 9:12 
AnswerRe: proposal Pin
VallarasuS2-Jul-11 18:37
VallarasuS2-Jul-11 18:37 
AnswerRe: proposal Pin
VallarasuS2-Jul-11 21:36
VallarasuS2-Jul-11 21:36 
SuggestionImage Pin
DaveAuld2-Jul-11 7:11
professionalDaveAuld2-Jul-11 7:11 
GeneralRe: Image Pin
VallarasuS2-Jul-11 7:27
VallarasuS2-Jul-11 7:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.