Saturday, April 18, 2009

Screenshot in 2 Clicks using .NET

Step 1: Fire up Visual Studio 2008 and Create a new Windows Application.
Step 2: From the toolbox, add a ‘ContextMenuStrip’ and a ‘NotifyIcon’ to the form.
Step 3: Choose an icon for the’ NotifyIcon’ using the Icon property. Change the ‘ContextMenuStrip’ property of the NotifyIcon to ‘contextMenuStrip1’ (which we added in Step 2)
Step 4: Add a new menu item to ContextMenuStrip1 control named “Grab Screenshot” as shown in the screen below:














Now double click this MenuItem and add the following code to its click event:
C#
private void grabScreenShotToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap bmpSS = null;
Graphics gfxSS = null;

try
{
bmpSS = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);

gfxSS = Graphics.FromImage(bmpSS);

gfxSS.CopyFromScreen(
Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);

SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "JPeg Image*.jpg";
saveDialog.Title = "Save Image as";
saveDialog.ShowDialog();
if (saveDialog.FileName != string.Empty)
bmpSS.Save(saveDialog.FileName, ImageFormat.Jpeg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}



Note: Make sure you import System.Drawing and System.Drawing.Imaging namespaces.
In the code above, we create a new Bitmap which is equal to the width and height of the primary screen and then we create a new graphics using the Bitmap. We then use the CopyFromScreen() to capture the screen. Once this step is done, we create an object of SaveFileDialog and display it to the user to choose the location and save the file as an .jpeg image.
Step 5: Add the following code to the Form load event which will hide the form and remove it from taskbar.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
this.Hide();
}



Now run the program and right click the Icon that appears in your status bar. Click on the ‘Grab ScreenShot’ and save the screenshot to the desired location.

The next time you want a screenshot, remember it’s just two clicks away!
The entire source code of this article can be downloaded from here.

No comments:

Post a Comment