using System;
using System.Drawing;
using System.Windows;
using System.Threading;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using Clipboard = System.Windows.Forms.Clipboard;
namespace SHJX.Service.Common.Utils
{
public static class ScreenUtil
{
public static Image CutScreen(this Rect rec)
{
PrintScreen();
Thread.Sleep(1000);
if (Clipboard.ContainsImage())
{
Image image = CutPicture(Clipboard.GetImage(), rec);
return image;
}
else
{
Console.WriteLine("clipboard doesn't contain picture");
return null;
}
}
private static Image CutPicture(Image image, Rect rec)
{
PrintScreen();
if (rec.X + rec.Width > image.Width)
rec.Width = image.Width - rec.X;
if (rec.Y + rec.Height > image.Height)
rec.Height = image.Height - rec.Y;
return image;
}
#region 系统调用
private const int VK_SNAPSHOT = 0x2C;
[DllImport("user32.dll")]
static extern void keybd_event
(
byte bVk,// 虚拟键值
byte bScan,// 硬件扫描码
uint dwFlags,// 动作标识
IntPtr dwExtraInfo// 与键盘动作关联的辅加信息
);
private static void PrintScreen()
{
keybd_event((byte)VK_SNAPSHOT, 0, 0x0, IntPtr.Zero);//down
System.Windows.Forms.Application.DoEvents();//强制窗口响应按钮事件
keybd_event((byte)VK_SNAPSHOT, 0, 0x2, IntPtr.Zero);//up
System.Windows.Forms.Application.DoEvents();
}
#endregion
#region 截图转换成Bitmap
///
/// 截图转换成bitmap
///
///
/// 默认控件宽度
/// 默认控件高度
/// 默认0
/// 默认0
///
public static Bitmap ScreenConvertToBitmap(this System.Windows.Media.Visual visual)
{
int width = 0, height = 0, x = 0, y = 0;
Rect rc = SystemParameters.WorkArea; //获取工作区大小
width = (int)rc.Width;
height = (int)rc.Height;
var rtb = new RenderTargetBitmap(width, height, x, y, System.Windows.Media.PixelFormats.Default);
rtb.Render(visual);
Bitmap bit = BitmapSourceToBitmap(rtb);
return bit;
}
///
/// BitmapSource转Bitmap
///
///
///
public static Bitmap BitmapSourceToBitmap(BitmapSource source)
{
return BitmapSourceToBitmap(source, source.PixelWidth, source.PixelHeight);
}
///
/// Convert BitmapSource to Bitmap
///
///
///
public static Bitmap BitmapSourceToBitmap(BitmapSource source, int width, int height)
{
Bitmap bmp = null;
try
{
PixelFormat format = PixelFormat.Format24bppRgb;
/*set the translate type according to the in param(source)*/
switch (source.Format.ToString())
{
case "Rgb24":
case "Bgr24": format = PixelFormat.Format24bppRgb; break;
case "Bgra32": format = PixelFormat.Format32bppPArgb; break;
case "Bgr32": format = PixelFormat.Format32bppRgb; break;
case "Pbgra32": format = PixelFormat.Format32bppArgb; break;
}
bmp = new Bitmap(width, height, format);
BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
ImageLockMode.WriteOnly,
format);
source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);
}
catch
{
if (bmp != null)
{
bmp.Dispose();
bmp = null;
}
}
return bmp;
}
#endregion
}
}