前言
- 在学习c# 的过程中,通过案例是比较高效的一种学习方式。下面我将介绍如何使用c#开发一个简单的windows桌面截图程序。这个程序实现了基本的屏幕截图功能,包括捕获全屏、预览图像以及保存截图文件。通过该案例,可以了解到windows窗体应用(winforms)的开发知识,并理解gdi+绘图技术、文件对话框的使用以及事件驱动编程的核心概念。
- 实现的功能虽然简单,但涵盖了实际开发中的关键流程,如ui设计、功能逻辑实现、异常处理等。
知识梳理
实现功能:
- 1、点击按钮截图。
- 2、截图显示、拖动缩放、功能。
- 3、截图保存。
实现步骤:
- 1、获取屏幕边界。
- 2、创建位图对象。
- 3、屏幕内容捕获
- 4、内容传递。
- 5、显示截图编辑器窗口。
核心方法1:
screen.getbounds(point)
- 该方法用于获取主显示器的边界矩形。
- 一般从屏幕左上角(0,0)开始计算。
核心方法2:
copyfromscreen(point,point,point)
- 该方法实现屏幕内容拷贝。
- 参数一:源位置左上角坐标。
- 参数二:目标位置左上角坐标。
- 参数三:要拷贝的区域大小。
自定义显示图像窗体:
frmscreenshoteditor
控件代码在文末链接,需要者自行下载。
运行效果
代码
主窗体代码
- 主窗体中添加截图按钮,实现点击按钮截图功能,在截图前隐藏该窗体主窗体,否则会截到主窗体,添加一定的延时,否则还是会截到主窗体,因为主窗体可能未隐藏成功。截图成功后再显示主窗体和子窗体。
public partial class mainform : form { public mainform() { initializecomponent(); this.centertoparent(); this.maximumsize = this.size; this.minimumsize = this.size; } private void btn_screenshot_click(object sender, eventargs e) { this.hide(); thread.sleep(500); screenshot(); } /// 截图方法 private void screenshot() { try { // 获取屏幕尺寸 rectangle bounds = screen.getbounds(point.empty); // 创建位图对象 using (bitmap bitmap = new bitmap(bounds.width, bounds.height)) { // 创建绘图对象 using (graphics g = graphics.fromimage(bitmap)) { // 将屏幕内容复制到位图中 g.copyfromscreen(point.empty, point.empty, bounds.size); } this.show(); //显示图像 frmscreenshoteditor frmscreenshoteditor = new frmscreenshoteditor(); frmscreenshoteditor.image = bitmap; frmscreenshoteditor.showdialog(); } } catch (exception ex) { messagebox.show($"截图失败: {ex.message}", "错误",messageboxbuttons.ok, messageboxicon.error); } } }
截图编辑窗体
- 在截图编辑子窗体中添加自定义图像显示控件,该控件需要实现图像的滚动和缩放功能。添加一个image属性,用于设置显示的图片。最后添加一个保存按钮,实现图像保存功能。
public partial class frmscreenshoteditor :winformbase { public image image { get => uvcanvas.image; set { uvcanvas.image = value; invalidate(); } } public frmscreenshoteditor() { initializecomponent(); this.centertoparent(); this.windowstate = formwindowstate.maximized; } private void btn_save_click(object sender, system.eventargs e) { savefiledialog savefiledialog = new savefiledialog(); savefiledialog.filename = "截图1"; //设置初始文件名 savefiledialog.filter= "png image|*.png|jpeg image|*.jpg|bmp image|*.bmp"; if (savefiledialog.showdialog()== dialogresult.ok) { string extension = path.getextension(savefiledialog.filename).tolower(); imageformat imageformat; switch (extension) { case ".png": imageformat = imageformat.png; break; case ".jpg": imageformat = imageformat.jpeg; break; case ".bmp": imageformat = imageformat.bmp; break; default: imageformat = imageformat.png; break; } try { image.save(savefiledialog.filename, imageformat); messagebox.show($"图片已成功保存至: {savefiledialog.filename}"); } catch (exception ex) { messagebox.show($"保存图片时出错: {ex.message}"); } } } }
总结
- 通过实现案例学习编程是一种高效的学习方法。这种学习方式将抽象概念具体化。通过上面的截图程序,我们实际应用了窗体控件、事件处理、gdi+绘图等核心知识点,比单纯学习理论更容易理解和记忆。
- 其次通过案例可以获得正向反馈,看到自己编写的代码真正实现功能,极大提升了学习动力和成就感。
- 最后,该案例后面可以自己扩展性,当你掌握了更多的基础知识后,可以逐步添加区域选择、图像编辑等更高级的功能。
最后
以上就是基于c#实现windows桌面截图功能的详细内容,更多关于c# windows桌面截图的资料请关注代码网其它相关文章!
发表评论