这篇文章介绍了C#实现截图帮助类的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
帮助类实现:
注意修改命名空间
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class ScreenCapture
{
private Bitmap _screenshot = null;
/// <summary>
/// 截取全屏
/// </summary>
/// <returns>返回值</returns>
public Bitmap CaptureScreen()
{
return Capture(Rectangle.Empty, false);
}
/// <summary>
/// 截取全屏并保存
/// </summary>
/// <param name="fileName">文件路径</param>
/// <returns></returns>
public Bitmap CaptureScreen(string fileName)
{
Bitmap screenshot = Capture(Rectangle.Empty, false);
saveImage(fileName, screenshot);
return screenshot;
}
/// <summary>
/// 截屏到剪切板
/// </summary>
public void CopyToClipboard()
{
if (this._screenshot != null)
Clipboard.SetImage(this._screenshot);
else if (this._screenshot == null)
MessageBox.Show("No screenshot found. Please take a screenshot first.", "Copy to Clipboard");
}
/// <summary>
/// 区域截屏
/// </summary>
/// <param name="rect">区域范围</param>
/// <returns>返回值</returns>
public Bitmap CaptureRectangle(Rectangle rect)
{
return Capture(rect, true);
}
/// <summary>
/// 区域截屏
/// </summary>
/// <param name="rect">区域范围</param>
/// <param name="fileName">文件路径</param>
/// <returns>返回值</returns>
public Bitmap CaptureRectangle(Rectangle rect, string fileName)
{
Bitmap screenshot = Capture(rect, true);
saveImage(fileName, screenshot);
return screenshot;
}
private Bitmap Capture(Rectangle rect, bool isRect)
{
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
Bitmap screenshot = null;
if(!isRect)
screenshot = new Bitmap(screenWidth, screenHeight);
else if(isRect)
screenshot = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(screenshot);
if (!isRect)
{
g.CopyFromScreen(Point.Empty, Point.Empty, screenshot.Size);
}
else if (isRect)
{
g.CopyFromScreen(new Point(rect.X, rect.Y), Point.Empty, rect.Size);
}
this._screenshot = screenshot;
return screenshot;
}
private void saveImage(string fileName, Bitmap screenshot)
{
string ext = System.IO.Path.GetExtension(fileName);;
ext = ext.ToLower();
if (ext == ".jpg" || ext == ".jpeg")
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
else if(ext == ".gif")
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);
else if(ext == ".png")
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
else if (ext == ".bmp")
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);
else if (ext == ".tiff")
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);
}
}
}
到此这篇关于C#实现截图帮助类的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#实现截图帮助类
基础教程推荐
猜你喜欢
- C# 调用WebService的方法 2023-03-09
- C#控制台实现飞行棋小游戏 2023-04-22
- winform把Office转成PDF文件 2023-06-14
- C# windows语音识别与朗读实例 2023-04-27
- 一个读写csv文件的C#类 2022-11-06
- C# List实现行转列的通用方案 2022-11-02
- unity实现动态排行榜 2023-04-27
- ZooKeeper的安装及部署教程 2023-01-22
- C#类和结构详解 2023-05-30
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26