我采用了Parox 代码并对其进行了修复,以减少错误并更适合 C# 语言编译器。
作为一名 C# 程序员,我可以说,代码抛出错误并不奇怪。有些部分甚至可能导致堆栈溢出或终止应用程序异常 - 但这是我们在此问答中所处的领域;)
长时间录制可能会导致Counter 溢出和覆盖从录制的第一秒获取的 PNG 以及可能的其他问题,但我认为最好将其附加到线程中以供其他人使用:
public class ScreenRecorder
{
// C:\Users\sebas.000\AppData\Local\Temp\snapshot
private static string tempSnapshotDir = Path.GetTempPath() + "snapshot\\";
private static Thread snapThread = new Thread(Snapshot);
private static bool flag = false;
private static Rectangle _Bounds = Screen.PrimaryScreen.Bounds;
public static Rectangle Bounds
{
get { return _Bounds; }
set { _Bounds = value; }
}
private static void Snapshot()
{
ClearRecording();
using (var memoryBitmap = new Bitmap(_Bounds.Width, _Bounds.Height, Imaging.PixelFormat.Format32bppArgb))
using (var graphSurface = Graphics.FromImage(memoryBitmap))
{
//var currentBounds = new Rectangle();
var Counter = (UInt64)0;
var freshPoint = new System.Drawing.Point();
flag = true;
do
{
Thread.Sleep(100);
graphSurface.CopyFromScreen(_Bounds.Location, freshPoint, _Bounds.Size);
// add cursor
//currentBounds.Size = Cursor.Current.Size;
//currentBounds.Location = System.Drawing.Point.Subtract(Cursor.Position, Bounds.Size);
//Cursors.Default.Draw(graphSurface, currentBounds);
Counter++;
var fileName = FormatFileName(Counter.ToString(), 6, '0', ".png");
using (var FS = new FileStream(string.Concat(tempSnapshotDir, fileName), FileMode.Create, FileAccess.Write))
{
memoryBitmap.Save(FS, ImageFormat.Png);
}
} while (flag);
}
}
private static void ClearRecording()
{
if (Directory.Exists(tempSnapshotDir))
Directory.Delete(tempSnapshotDir, true);
Directory.CreateDirectory(tempSnapshotDir);
}
public static void StartRecording()
{
//snapThread = new Thread(Snapshot);
snapThread.Start();
}
public static void StopRecording()
{
flag = false;
snapThread.Join();
}
public static void Save(string outpuFinlename)
{
var gifBitmapEncoder = new GifBitmapEncoder();
var fileStreamList = new List<FileStream>();
// encode GIF from PNGs
foreach (string pngFile in Directory.GetFiles(tempSnapshotDir, "*.png", SearchOption.TopDirectoryOnly)) // efficiency !!! create list like Counter !!!
{
var tempStream = new FileStream(pngFile, FileMode.Open);
var bitmapFrame = BitmapFrame.Create(tempStream);
fileStreamList.Add(tempStream);
gifBitmapEncoder.Frames.Add(bitmapFrame);
}
// save GIF to disk
using (var fileStream = new FileStream(outpuFinlename, FileMode.Create, FileAccess.Write))
{
gifBitmapEncoder.Save(fileStream);
}
fileStreamList.Clear();
ClearRecording();
}
private static string FormatFileName(string S, int places, char character, string extension)
{
if (S.Length >= places)
return S;
return S.PadLeft(places, '0') + extension;
}
}