以下代码是截取屏幕并保存文件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.IO;namespace ScreenGame
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private Graphics g; private void button1_Click(object sender, EventArgs e)
{
int i,m,n;
int Old_x, Old_y; m = Screen.PrimaryScreen.Bounds.Width;
n = Screen.PrimaryScreen.Bounds.Height; Old_x = Convert.ToInt32(textBoxX.Text);
Old_y = Convert.ToInt32(textBoxY.Text);
Size imgs = new Size(m - Old_x, n - Old_y);
//创建位图对象,这里通过指定图片的宽度和高度创建空白的图片,这里用于截取整个屏幕,所以要获取显示器的宽度和高度
Bitmap map = new Bitmap(m, n);
//通过位图对象创建Graphics对象,该对象用于画图
Graphics gh = Graphics.FromImage(map);
//通过Graphics对象从屏幕上将整个屏幕截取下来,这里不能截取鼠标
gh.CopyFromScreen(Old_x, Old_y, 0, 0, imgs);
//创建一个内存流,用于暂时保存图片并将图片转换成字节数组
MemoryStream ms = new MemoryStream();
map.Save("tmp.png", System.Drawing.Imaging.ImageFormat.Png); ///第二次执行时,此行报错,原因可能是tmp.png文件还在被占用。
map.Dispose();
//加载图片,显示切图结果
pictureBox1.Image = Image.FromFile("tmp.png");
} private void btnZoom_Click(object sender, EventArgs e)
{
//重新加载图片
pictureBox1.Image = Image.FromFile("tmp.png");
} private void btnClear_Click(object sender, EventArgs e)
{
//清除图片
pictureBox1.Image = null;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.IO;namespace ScreenGame
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private Graphics g; private void button1_Click(object sender, EventArgs e)
{
int i,m,n;
int Old_x, Old_y; m = Screen.PrimaryScreen.Bounds.Width;
n = Screen.PrimaryScreen.Bounds.Height; Old_x = Convert.ToInt32(textBoxX.Text);
Old_y = Convert.ToInt32(textBoxY.Text);
Size imgs = new Size(m - Old_x, n - Old_y);
//创建位图对象,这里通过指定图片的宽度和高度创建空白的图片,这里用于截取整个屏幕,所以要获取显示器的宽度和高度
Bitmap map = new Bitmap(m, n);
//通过位图对象创建Graphics对象,该对象用于画图
Graphics gh = Graphics.FromImage(map);
//通过Graphics对象从屏幕上将整个屏幕截取下来,这里不能截取鼠标
gh.CopyFromScreen(Old_x, Old_y, 0, 0, imgs);
//创建一个内存流,用于暂时保存图片并将图片转换成字节数组
MemoryStream ms = new MemoryStream();
map.Save("tmp.png", System.Drawing.Imaging.ImageFormat.Png); ///第二次执行时,此行报错,原因可能是tmp.png文件还在被占用。
map.Dispose();
//加载图片,显示切图结果
pictureBox1.Image = Image.FromFile("tmp.png");
} private void btnZoom_Click(object sender, EventArgs e)
{
//重新加载图片
pictureBox1.Image = Image.FromFile("tmp.png");
} private void btnClear_Click(object sender, EventArgs e)
{
//清除图片
pictureBox1.Image = null;
}
}
}
Bitmap map2 = new Bitmap(m, n);
gh = Graphics.FromImage(map);
gh.DrawImage(map,0,0);
pictureBox1.Image = (Image)map2;
gh.Dispose();
map.Dispose();