界面如下:
下面放了一个PictureBox
首先是声明函数:
//这里是调用 Windows API函数来进行截图
//首先导入库文件
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")] //声明函数
private static extern IntPtr CreateDC
(
string Driver, //驱动名称
string Device, //设备名称
string Output, //无用,可以设定为null
IntPtr PrintData //任意的打印机数据
); [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest, //目标设备的句柄
int XDest, //目标对象的左上角X坐标
int YDest, //目标对象的左上角的Y坐标
int Width, //目标对象的宽度
int Height, //目标对象的高度
IntPtr hdcScr, //源设备的句柄
int XScr, //源设备的左上角X坐标
int YScr, //源设备的左上角Y坐标
Int32 drRop //光栅的操作值 );
截图按钮事件代码:
private void button1_Click(object sender, EventArgs e)
{
//创建显示器的DC
IntPtr dcScreen = CreateDC("DISPLAY", null, null, (IntPtr)null); //由一个指定设备的句柄创建一个新的Graphics对象
Graphics g1 = Graphics.FromHdc(dcScreen);
int tmpWidth, tmpHeigth; //获得保存图片的质量
long level = long.Parse(this.textBox5.Text); //如果是全屏捕获
if(this.radioButton1.Checked == true)
{
tmpWidth = Screen.PrimaryScreen.Bounds.Width;
tmpHeigth = Screen.PrimaryScreen.Bounds.Height;
Image MyImage = new Bitmap(tmpWidth, tmpHeigth, g1); //创建位图图形对象
Graphics g2 = Graphics.FromImage(MyImage);
//获得窗体的上下文设备
IntPtr dc1 = g1.GetHdc();
//获得位图文件的上下文设备
IntPtr dc2 = g2.GetHdc(); //写入到位图
BitBlt(dc2, , , tmpWidth, tmpHeigth, dc1, , , ); //释放窗体的上下文设备
g1.ReleaseHdc(dc1);
//释放位图的上下文设备
g2.ReleaseHdc(dc2); //保存图像并显示
SaveImageWithQuality(MyImage,level);
this.pictureBox1.Image = MyImage; }
else
{
int X = Convert.ToInt32(this.textBox1.Text);
int Y = Convert.ToInt32(this.textBox2.Text);
int Width = Convert.ToInt32(this.textBox3.Text);
int Height = Convert.ToInt32(this.textBox4.Text); Image Myimage = new Bitmap(Width, Height,g1);
Graphics g2 = Graphics.FromImage(Myimage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc(); BitBlt(dc2,,,Width,Height,dc1,X,Y,);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2); SaveImageWithQuality(Myimage, level);
this.pictureBox1.Image = Myimage; }
}
设置图片质量的函数,详细介绍:http://www.cnblogs.com/zhaotianff/p/5570321.html
//保存图片时设置质量
private void SaveImageWithQuality(Image bmp,long level)
{ ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters();
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, level);
myEncoderParameters.Param[] = myEncoderParameter;
bmp.Save(@"test.jpg", jgpEncoder, myEncoderParameters); } private ImageCodecInfo GetEncoder(ImageFormat format)
{ ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
运行效果:
可惜把自己也截出来了,正在寻找方法不把自己截出来,哈哈。