admin管理员组文章数量:1559385
使用 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);
}
}
}
本文标签: 截屏
版权声明:本文标题:C# 截屏 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1727402844a1113053.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论