C#實現截圖功能

huanglg發表於2024-05-09

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

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

private void button1_Click(object sender, EventArgs e)
{
Bitmap bitmap = CaptureActiveScreen();
bitmap.Save("screenshot.png", ImageFormat.Png);
}

public Bitmap CaptureActiveScreen()
{
// 建立一個和當前螢幕一樣大小的Bitmap
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

// 建立一個畫布
Graphics g = Graphics.FromImage(bmp);

// 擷取整個螢幕
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);

// 釋放畫布資源
g.Dispose();

return bmp;
}
}
}

相關文章