Thursday, July 3, 2008

C# screen capture

This is achieved by calling windows API functions.
Also see Reference.

using System.Runtime.InteropServices;
using System.Drawing.Imaging;

public class Form1 : System.Windows.Forms.Form {
#region Dll Imports
[DllImport("user32.dll")]
private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);
#endregion

private void screen_capture() {
try {
Bitmap bm = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(bm);
IntPtr hdc = g.GetHdc();
Form1.PrintWindow(this.Handle, hdc, 0);
//MessageBox.Show("color: " + bm.GetPixel(550, 300));
g.ReleaseHdc(hdc);
g.Flush();
g.Dispose();
//this.pictureBox1.Image = bm;
bm.Save("test.bmp");
} catch (Exception e) {
MessageBox.Show(this, "error: " + e.Message);
}
}

public Form1() { InitializeComponent(); /* screen_capture(); */ }

[STAThread]
static void Main() { Application.Run(new Form1()); }
}

No comments:

Blog Archive

Followers