使用 Graphics.CopyFromScreen api实现截屏
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public class jiePing
{
[DllImport("User32.dll", EntryPoint = "GetDC")]
private extern static IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
const int DESKTOPVERTRES = 117;
const int DESKTOPHORZRES = 118;
/// <summary>
/// 截屏为Bitmap
/// </summary>
/// <returns></returns>
public static Bitmap GetScreenCapture()
{
//获取屏幕大小的几种方式,具体效果可自行测试 // Screen.PrimaryScreen.Bounds // SystemInformation.PrimaryMonitorMaximizedWindowSize // SystemInformation.PrimaryMonitorSize // SystemInformation.WorkingArea // SystemInformation.VirtualScreen //此处不使用以上方式,因为在DPI有调整的情况下,获取到的分辨率有问题
IntPtr hdc = GetDC(IntPtr.Zero);
int w = GetDeviceCaps(hdc, DESKTOPHORZRES);
int h = GetDeviceCaps(hdc, DESKTOPVERTRES);
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format32bppRgb);
using (Graphics g = Graphics.FromImage(bmp))
{ //绘制屏幕
g.CopyFromScreen(0, 0, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
}
//pictureBox1.Image = bmp;
// image.Source = jiePing.BitmapToBitmapImage(bmp);
return bmp;
}
/// <summary>
/// 格式转换 bitmap->BitmapImage
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static System.Windows.Media.Imaging.BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
Bitmap b = new Bitmap(bitmap);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] bytes = ms.GetBuffer(); //byte[] bytes= ms.ToArray(); 这两句都可以
ms.Close();
//Convert it to BitmapImage
System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(bytes);
image.EndInit();
return image;
}
}
调用
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
image.Source = jiePing.BitmapToBitmapImage( jiePing.GetScreenCapture());
jiePing.GetScreenCapture().Save("D:/65.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
}