window form 截屏

来源:互联网 发布:淘宝正品代购推荐 编辑:程序博客网 时间:2024/06/17 18:16

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]    private static extern bool BitBlt(   IntPtr hdcDest, // 目标 DC的句柄   int nXDest,   int nYDest,   int nWidth,   int nHeight,   IntPtr hdcSrc,  // 源DC的句柄   int nXSrc,   int nYSrc,   System.Int32 dwRop  // 光栅的处理数值   );    [System.Runtime.InteropServices.DllImport("gdi32.dll")]    public static extern IntPtr CreateDC(string driver, string device, IntPtr res1, IntPtr res2);    private void button1_Click(object sender, EventArgs e)    {        GetScreen1();        GetScreen2();    }    public static void GetScreen1()    {        //截取屏幕内容             Size screen = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);        Bitmap memoryImage = new Bitmap(screen.Width, screen.Height);        Graphics memoryGraphics = Graphics.FromImage(memoryImage);        //  memoryGraphics.CopyFromScreen(0, 0, 0, 0, screen, CopyPixelOperation.SourceCopy);        memoryGraphics.CopyFromScreen(0, 0, 0, 0, screen);        //memoryImage          memoryImage.Save(@"screen.jpg", ImageFormat.Jpeg);        MemoryStream data = new MemoryStream();        //  memoryImage.Save(data, ImageFormat.Png);    }    public static void GetScreen2()    {        //截取屏幕内容             Rectangle rect = new Rectangle();        //    rect = Screen.GetWorkingArea(this);        rect = Screen.PrimaryScreen.Bounds;        //创建一个以当前屏幕为模板的图象        IntPtr dcTmp = CreateDC("DISPLAY", "DISPLAY", (IntPtr)null, (IntPtr)null);        Graphics g1 = Graphics.FromHdc(dcTmp);        //创建以屏幕大小为标准的位图         Image MyImage = new Bitmap(rect.Width, rect.Height, g1);        Graphics g2 = Graphics.FromImage(MyImage);        //得到屏幕的DC        IntPtr dc1 = g1.GetHdc();        //得到Bitmap的DC         IntPtr dc2 = g2.GetHdc();        //调用此API函数,实现屏幕捕获        //  BitBlt(dc2, 0, 0, rect.Width, rect.Height, dc1, 0, 0, 13369376);        BitBlt(dc2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, dc1, 0, 0, 13369376);        //释放掉屏幕的DC        g1.ReleaseHdc(dc1);        //释放掉Bitmap的DC         g2.ReleaseHdc(dc2);        //以JPG文件格式来保存        MyImage.Save("text.jpg", ImageFormat.Jpeg);        string a = "当前屏幕已经保存";        MessageBox.Show(a);    }}

}