// 屏幕录制 - 绿色工具箱 // 单文件零依赖(只用 GDI+ 抓屏 + 手写 MJPEG AVI 容器),C# 5.0 语法 // 功能:全屏或拖框选区录制,帧率 5/10/15/20 可选,输出标准 AVI(MJPEG),Windows 自带播放器可放 // 边界:无声录制(不做音频混流);帧率是「尽力而为」,机器忙时会掉帧;单文件上限 2GB // 安全:只抓屏幕像素,不联网、不上传、不注入 using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Threading; using System.Windows.Forms; namespace GreenToolbox { // 手写 MJPEG AVI:RIFF/AVI + hdrl(avih+strl(strh+strf)) + movi + idx1 public class MjpegAviWriter : IDisposable { FileStream _fs; BinaryWriter _w; int _width, _height, _fps, _quality; long _moviDataStart; // 'movi' 四字符之后的位置 long _frameStart; List _offsets = new List(); List _sizes = new List(); long _posRiffSize = 4, _posHdrlSize = 16, _posStrlSize = 92, _posMoviSize = 216; long _posTotalFrames = 48, _posStreamLength = 140; long _hdrlEnd; bool _closed; long _finalBytes; public int FrameCount { get { return _offsets.Count; } } public long BytesWritten { get { return _closed ? _finalBytes : (_fs == null ? 0 : _fs.Length); } } public MjpegAviWriter(string path, int width, int height, int fps, int quality) { if (width < 16) width = 16; if (height < 16) height = 16; width = width / 2 * 2; // MJPG 宽高取偶数,兼容性最好 height = height / 2 * 2; _width = width; _height = height; _fps = fps; _quality = quality; _fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite); _w = new BinaryWriter(_fs); // RIFF _w.Write(Encoding.ASCII.GetBytes("RIFF")); _w.Write((uint)0); // 回填 _w.Write(Encoding.ASCII.GetBytes("AVI ")); // LIST hdrl _w.Write(Encoding.ASCII.GetBytes("LIST")); _w.Write((uint)0); // 回填 _w.Write(Encoding.ASCII.GetBytes("hdrl")); // avih _w.Write(Encoding.ASCII.GetBytes("avih")); _w.Write((uint)56); _w.Write((uint)(1000000 / Math.Max(1, fps))); _w.Write((uint)0); // max bytes/sec 回填时估算 _w.Write((uint)0); // padding _w.Write((uint)0x10); // AVIF_HASINDEX _w.Write((uint)0); // total frames 回填 _w.Write((uint)0); // initial frames _w.Write((uint)1); // streams _w.Write((uint)(width * height * 3)); _w.Write((uint)width); _w.Write((uint)height); for (int i = 0; i < 4; i++) _w.Write((uint)0); // LIST strl _w.Write(Encoding.ASCII.GetBytes("LIST")); _w.Write((uint)0); // 回填 _w.Write(Encoding.ASCII.GetBytes("strl")); // strh _w.Write(Encoding.ASCII.GetBytes("strh")); _w.Write((uint)56); _w.Write(Encoding.ASCII.GetBytes("vids")); _w.Write(Encoding.ASCII.GetBytes("MJPG")); _w.Write((uint)0); // flags _w.Write((ushort)0); // priority _w.Write((ushort)0); // language _w.Write((uint)0); // initial frames _w.Write((uint)1); // scale _w.Write((uint)fps); // rate _w.Write((uint)0); // start _w.Write((uint)0); // length 回填 _w.Write((uint)(width * height * 3)); _w.Write((uint)0xFFFFFFFF); // quality = -1 _w.Write((uint)0); // sample size _w.Write((ushort)0); _w.Write((ushort)0); _w.Write((ushort)width); _w.Write((ushort)height); // strf (BITMAPINFOHEADER) _w.Write(Encoding.ASCII.GetBytes("strf")); _w.Write((uint)40); _w.Write((uint)40); _w.Write((int)width); _w.Write((int)height); _w.Write((ushort)1); _w.Write((ushort)24); _w.Write(Encoding.ASCII.GetBytes("MJPG")); _w.Write((uint)(width * height * 3)); _w.Write((int)0); _w.Write((int)0); _w.Write((uint)0); _w.Write((uint)0); _hdrlEnd = _fs.Position; // = 212,hdrl 到这里结束 // LIST movi _w.Write(Encoding.ASCII.GetBytes("LIST")); _w.Write((uint)0); // 回填 _w.Write(Encoding.ASCII.GetBytes("movi")); _moviDataStart = _fs.Position; _frameStart = _moviDataStart; _w.Flush(); } public void AddFrame(byte[] jpeg) { if (_closed) throw new ObjectDisposedException("MjpegAviWriter"); long rel = _fs.Position - _moviDataStart; _w.Write(Encoding.ASCII.GetBytes("00dc")); _w.Write((uint)jpeg.Length); _w.Write(jpeg); if ((jpeg.Length & 1) == 1) _w.Write((byte)0); // 块补齐到偶数 _offsets.Add(rel); _sizes.Add(jpeg.Length); _w.Flush(); } public void AddFrame(Bitmap bmp) { AddFrame(EncodeJpeg(bmp, _quality)); } public static byte[] EncodeJpeg(Bitmap bmp, int quality) { ImageCodecInfo codec = null; foreach (ImageCodecInfo c in ImageCodecInfo.GetImageEncoders()) if (c.FormatID == ImageFormat.Jpeg.Guid) { codec = c; break; } using (EncoderParameters ps = new EncoderParameters(1)) { ps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); using (MemoryStream ms = new MemoryStream()) { bmp.Save(ms, codec, ps); return ms.ToArray(); } } } public void Close() { if (_closed) return; _closed = true; long endMovi = _fs.Position; // idx1 _w.Write(Encoding.ASCII.GetBytes("idx1")); _w.Write((uint)(16 * _offsets.Count)); for (int i = 0; i < _offsets.Count; i++) { _w.Write(Encoding.ASCII.GetBytes("00dc")); _w.Write((uint)0x10); // AVIIF_KEYFRAME _w.Write((uint)_offsets[i]); _w.Write((uint)_sizes[i]); } _w.Flush(); long fileLen = _fs.Length; // 回填各处长度 _fs.Position = _posRiffSize; _w.Write((uint)(fileLen - 8)); // RIFF 的 LIST 长度包含 4 字节 form type('hdrl' / 'strl' / 'movi' 本身) _fs.Position = _posHdrlSize; _w.Write((uint)(_hdrlEnd - 20)); // 从 'hdrl' 四字符到 LIST 结束 _fs.Position = _posStrlSize; _w.Write((uint)(_hdrlEnd - 96)); // 从 'strl' 四字符到 LIST 结束 _fs.Position = _posMoviSize; _w.Write((uint)(endMovi - _moviDataStart + 4)); _fs.Position = _posTotalFrames; _w.Write((uint)_offsets.Count); _fs.Position = _posStreamLength; _w.Write((uint)_offsets.Count); _fs.Position = 36; // avih.dwMaxBytesPerSec long avg = _offsets.Count == 0 ? 0 : (long)((endMovi - _moviDataStart) / _offsets.Count * _fps); _w.Write((uint)Math.Min(avg, uint.MaxValue)); _w.Flush(); _finalBytes = fileLen; _w.Dispose(); _fs.Dispose(); } public void Dispose() { Close(); } } public static class RecOps { public static string FpsText(int fps) { return fps + " 帧/秒"; } public static Rectangle NormalizeRect(Point a, Point b) { int x = Math.Min(a.X, b.X); int y = Math.Min(a.Y, b.Y); int w = Math.Abs(a.X - b.X); int h = Math.Abs(a.Y - b.Y); return new Rectangle(x, y, w, h); } public static bool RectOk(Rectangle r) { return r.Width >= 16 && r.Height >= 16; } // 按比例缩放(不放大),宽高一律取偶数,MJPG 兼容性最好 public static Size ScaleSize(int w, int h, double k) { if (w <= 0 || h <= 0) return new Size(16, 16); if (k <= 0 || k > 1) k = 1; int nw = (int)Math.Round(w * k); int nh = (int)Math.Round(h * k); if (nw < 16) nw = 16; if (nh < 16) nh = 16; return new Size(nw / 2 * 2, nh / 2 * 2); } public static string DurationText(TimeSpan t) { int s = (int)t.TotalSeconds; return (s / 60).ToString("00") + ":" + (s % 60).ToString("00"); } public static string SizeText(long b) { if (b < 1024) return b + " B"; if (b < 1024 * 1024) return (b / 1024.0).ToString("0.0") + " KB"; if (b < 1024L * 1024 * 1024) return (b / 1024.0 / 1024.0).ToString("0.0") + " MB"; return (b / 1024.0 / 1024.0 / 1024.0).ToString("0.00") + " GB"; } } // 拖框选区:全屏半透明遮罩,拖出矩形,回车确认,Esc 取消 public class RegionForm : Form { Point _start; bool _dragging; Rectangle _rect; public Rectangle Selected { get { return _rect; } } public RegionForm() { FormBorderStyle = FormBorderStyle.None; StartPosition = FormStartPosition.Manual; Bounds = SystemInformation.VirtualScreen; TopMost = true; BackColor = Color.Black; Opacity = 0.28; Cursor = Cursors.Cross; DoubleBuffered = true; KeyPreview = true; MouseDown += delegate(object s, MouseEventArgs e) { _start = e.Location; _dragging = true; _rect = new Rectangle(e.Location, Size.Empty); Invalidate(); }; MouseMove += delegate(object s, MouseEventArgs e) { if (!_dragging) return; _rect = RecOps.NormalizeRect(_start, e.Location); Invalidate(); }; MouseUp += delegate { _dragging = false; if (RecOps.RectOk(_rect)) DialogResult = DialogResult.OK; else Invalidate(); }; KeyDown += delegate(object s, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) DialogResult = DialogResult.Cancel; if (e.KeyCode == Keys.Enter && RecOps.RectOk(_rect)) DialogResult = DialogResult.OK; }; Paint += delegate(object s, PaintEventArgs e) { using (Pen p = new Pen(Color.FromArgb(80, 220, 150), 2)) { e.Graphics.DrawRectangle(p, _rect); string t = _rect.Width + " × " + _rect.Height + " 松开鼠标开始,Esc 取消"; e.Graphics.DrawString(t, new Font("Microsoft YaHei UI", 10f), Brushes.White, _rect.X + 6, Math.Max(0, _rect.Y - 24)); } }; } } public class RecForm : Form { Button _full, _region, _start, _stop, _open; ComboBox _fps, _scale, _quality; Label _status, _timerLabel, _recInfo; Rectangle _rect; bool _recording; Thread _worker; volatile bool _stopFlag; Stopwatch _sw = new Stopwatch(); System.Windows.Forms.Timer _ui; string _outPath = ""; int _frames; public RecForm() { Text = "屏幕录制 - 绿色工具箱"; ClientSize = new Size(600, 420); MinimumSize = new Size(560, 380); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9f); BackColor = Color.White; Label title = new Label(); title.Text = "屏幕录制(无声)"; title.Font = new Font("Microsoft YaHei UI", 14f, FontStyle.Bold); title.SetBounds(16, 12, 300, 30); Label hint = new Label(); hint.Text = "输出标准 AVI(MJPEG)文件,双击就能用系统播放器看;不含声音。"; hint.ForeColor = Color.FromArgb(110, 110, 110); hint.SetBounds(16, 44, 560, 20); GroupBox gArea = new GroupBox(); gArea.Text = "录制范围"; gArea.SetBounds(16, 70, 568, 96); _full = new Button(); _full.Text = "整个屏幕"; _full.SetBounds(14, 24, 120, 34); _full.Click += delegate { Rectangle vs = SystemInformation.VirtualScreen; _rect = new Rectangle(vs.X, vs.Y, vs.Width, vs.Height); ShowRect(); }; _region = new Button(); _region.Text = "拖框选择区域"; _region.SetBounds(144, 24, 140, 34); _region.Click += delegate { PickRegion(); }; _recInfo = new Label(); _recInfo.SetBounds(300, 30, 250, 22); _recInfo.Text = "未选择范围"; _recInfo.ForeColor = Color.FromArgb(110, 110, 110); Label note = new Label(); note.Text = "提示:录制全屏时建议先最小化本窗口;选区时按 Esc 可取消。"; note.ForeColor = Color.FromArgb(150, 150, 150); note.SetBounds(14, 64, 540, 20); GroupBox gSet = new GroupBox(); gSet.Text = "参数"; gSet.SetBounds(16, 176, 568, 78); Label l1 = new Label(); l1.Text = "帧率"; l1.SetBounds(14, 30, 36, 20); _fps = new ComboBox(); _fps.DropDownStyle = ComboBoxStyle.DropDownList; _fps.Items.AddRange(new object[] { "5 帧/秒", "10 帧/秒", "15 帧/秒", "20 帧/秒" }); _fps.SelectedIndex = 1; _fps.SetBounds(52, 27, 100, 24); Label l2 = new Label(); l2.Text = "缩放"; l2.SetBounds(176, 30, 36, 20); _scale = new ComboBox(); _scale.DropDownStyle = ComboBoxStyle.DropDownList; _scale.Items.AddRange(new object[] { "原始大小", "缩到 75%", "缩到 50%" }); _scale.SelectedIndex = 0; _scale.SetBounds(214, 27, 110, 24); Label l3 = new Label(); l3.Text = "画质"; l3.SetBounds(348, 30, 36, 20); _quality = new ComboBox(); _quality.DropDownStyle = ComboBoxStyle.DropDownList; _quality.Items.AddRange(new object[] { "省空间(60)", "均衡(80)", "清晰(92)" }); _quality.SelectedIndex = 1; _quality.SetBounds(386, 27, 120, 24); _start = new Button(); _start.Text = "开始录制"; _start.SetBounds(16, 272, 160, 44); _start.Font = new Font("Microsoft YaHei UI", 11f, FontStyle.Bold); _start.BackColor = Color.FromArgb(37, 148, 92); _start.ForeColor = Color.White; _start.FlatStyle = FlatStyle.Flat; _start.Click += delegate { StartRec(); }; _stop = new Button(); _stop.Text = "停止"; _stop.SetBounds(186, 272, 110, 44); _stop.Enabled = false; _stop.Click += delegate { StopRec(); }; _open = new Button(); _open.Text = "打开输出目录"; _open.SetBounds(306, 272, 130, 44); _open.Click += delegate { string dir = Path.GetDirectoryName(Application.ExecutablePath) + "\\录像"; try { Directory.CreateDirectory(dir); } catch { } System.Diagnostics.Process.Start("explorer.exe", "\"" + dir + "\""); }; _timerLabel = new Label(); _timerLabel.SetBounds(16, 330, 300, 40); _timerLabel.Text = "00:00"; _timerLabel.Font = new Font("Consolas", 22f, FontStyle.Bold); _timerLabel.ForeColor = Color.FromArgb(60, 60, 60); _status = new Label(); _status.SetBounds(200, 340, 380, 24); _status.Text = "待机"; _status.ForeColor = Color.FromArgb(110, 110, 110); Controls.Add(title); Controls.Add(hint); Controls.Add(gArea); Controls.Add(gSet); Controls.Add(_start); Controls.Add(_stop); Controls.Add(_open); Controls.Add(_timerLabel); Controls.Add(_status); gArea.Controls.Add(_full); gArea.Controls.Add(_region); gArea.Controls.Add(_recInfo); gArea.Controls.Add(note); gSet.Controls.Add(l1); gSet.Controls.Add(_fps); gSet.Controls.Add(l2); gSet.Controls.Add(_scale); gSet.Controls.Add(l3); gSet.Controls.Add(_quality); Controls.SetChildIndex(gArea, 0); Controls.SetChildIndex(gSet, 1); Controls.SetChildIndex(_status, 2); Controls.SetChildIndex(_timerLabel, 3); Controls.SetChildIndex(_open, 4); Controls.SetChildIndex(_stop, 5); Controls.SetChildIndex(_start, 6); _ui = new System.Windows.Forms.Timer(); _ui.Interval = 200; _ui.Tick += delegate { UpdateUi(); }; _ui.Start(); FormClosing += delegate { StopRec(); }; } string OutDir { get { string dir = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "录像"); try { Directory.CreateDirectory(dir); } catch { dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "绿色工具箱录像"); Directory.CreateDirectory(dir); } return dir; } } void ShowRect() { _recInfo.Text = "已选 " + _rect.Width + " × " + _rect.Height; _recInfo.ForeColor = Color.FromArgb(37, 148, 92); } void PickRegion() { Hide(); Thread.Sleep(180); try { using (RegionForm f = new RegionForm()) { if (f.ShowDialog() == DialogResult.OK) { _rect = f.Selected; ShowRect(); } } } finally { Show(); Activate(); } } int Fps { get { return 5 + _fps.SelectedIndex * 5; } } int Quality { get { return _quality.SelectedIndex == 0 ? 60 : (_quality.SelectedIndex == 2 ? 92 : 80); } } double ScaleFactor { get { return _scale.SelectedIndex == 1 ? 0.75 : (_scale.SelectedIndex == 2 ? 0.5 : 1.0); } } void StartRec() { if (_recording) return; if (_rect.Width < 16 || _rect.Height < 16) { MessageBox.Show("先选一个录制范围(整个屏幕或拖框)。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string name = "录像_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".avi"; _outPath = Path.Combine(OutDir, name); _frames = 0; _stopFlag = false; _recording = true; _start.Enabled = false; _stop.Enabled = true; _sw.Reset(); _sw.Start(); _status.Text = "录制中 → " + _outPath; _worker = new Thread(new ThreadStart(Worker)); _worker.IsBackground = true; _worker.SetApartmentState(ApartmentState.STA); _worker.Start(); } void Worker() { Rectangle rect = _rect; int fps = 5; int quality = 80; double scale = 1.0; try { Invoke(new MethodInvoker(delegate { fps = Fps; quality = Quality; scale = ScaleFactor; })); } catch { } Size size = RecOps.ScaleSize(rect.Width, rect.Height, scale); int frameMs = 1000 / fps; try { using (MjpegAviWriter w = new MjpegAviWriter(_outPath, size.Width, size.Height, fps, quality)) { Stopwatch frameSw = new Stopwatch(); while (!_stopFlag) { frameSw.Reset(); frameSw.Start(); using (Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(rect.X, rect.Y, 0, 0, new Size(size.Width, size.Height), CopyPixelOperation.SourceCopy); } w.AddFrame(bmp); } _frames = w.FrameCount; if (w.BytesWritten > 1900L * 1024 * 1024) break; // 2GB 上限保护 int spend = (int)frameSw.ElapsedMilliseconds; int wait = frameMs - spend; if (wait > 0) Thread.Sleep(wait); } w.Close(); } SetStatus("已保存:" + Path.GetFileName(_outPath) + "(" + _frames + " 帧)", true); } catch (Exception ex) { SetStatus("录制失败:" + ex.Message, false); } finally { _recording = false; try { Invoke(new MethodInvoker(delegate { _start.Enabled = true; _stop.Enabled = false; })); } catch { } } } void SetStatus(string text, bool ok) { try { Invoke(new MethodInvoker(delegate { _status.Text = text; _status.ForeColor = ok ? Color.FromArgb(37, 148, 92) : Color.FromArgb(200, 70, 60); })); } catch { } } void StopRec() { if (!_recording) return; _stopFlag = true; _sw.Stop(); _status.Text = "正在保存…"; _status.ForeColor = Color.FromArgb(110, 110, 110); if (_worker != null && _worker.IsAlive) { if (!_worker.Join(8000)) { /* 让后台自己收尾 */ } } _start.Enabled = true; _stop.Enabled = false; } void UpdateUi() { if (_recording) _timerLabel.Text = RecOps.DurationText(_sw.Elapsed); if (_frames > 0 && _recording) { long bytes = 0; try { if (File.Exists(_outPath)) bytes = new FileInfo(_outPath).Length; } catch { } _status.Text = "录制中 " + _frames + " 帧 " + RecOps.SizeText(bytes); } } } public static class RecSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("屏幕录制 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string root = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-rec") : dir; try { if (Directory.Exists(root)) Directory.Delete(root, true); Directory.CreateDirectory(root); Check("矩形标准化:反向拖也对", RecOps.NormalizeRect(new Point(200, 150), new Point(50, 30)), new Rectangle(50, 30, 150, 120).ToString()); Check("矩形太小不认", RecOps.RectOk(new Rectangle(0, 0, 10, 10)), false); Check("矩形 16x16 可以", RecOps.RectOk(new Rectangle(0, 0, 16, 16)), true); Size s = RecOps.ScaleSize(1920, 1080, 0.75); Check("缩放 75% 宽度", s.Width, 1440); Check("缩放 75% 高度", s.Height, 810); Check("原始比例不动尺寸", RecOps.ScaleSize(800, 600, 1.0).Width, 800); Check("奇数宽取偶数", RecOps.ScaleSize(801, 601, 1.0).Width, 800); Check("缩放 50%", RecOps.ScaleSize(1000, 500, 0.5).Width, 500); Check("比例超 1 不放大", RecOps.ScaleSize(300, 200, 3.0).Width, 300); Check("时长 65 秒", RecOps.DurationText(TimeSpan.FromSeconds(65)), "01:05"); Check("体积 2MB", RecOps.SizeText(2 * 1024 * 1024), "2.0 MB"); // 真实写一个 3 帧 AVI(用 GDI 生成图再压 JPEG) string avi = Path.Combine(root, "test.avi"); using (MjpegAviWriter w = new MjpegAviWriter(avi, 64, 48, 10, 80)) { for (int i = 0; i < 3; i++) { using (Bitmap bmp = new Bitmap(64, 48, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.FromArgb(30 + i * 60, 120, 200)); g.DrawString("帧 " + i, new Font("Arial", 10f), Brushes.White, 4, 4); } w.AddFrame(bmp); } } Check("写入帧数统计", w.FrameCount, 3); w.Close(); } Check("AVI 文件存在", File.Exists(avi), true); long len = new FileInfo(avi).Length; Check("文件不是空的", len > 500, true); byte[] data = File.ReadAllBytes(avi); Check("RIFF 标识", Encoding.ASCII.GetString(data, 0, 4), "RIFF"); Check("类型 AVI", Encoding.ASCII.GetString(data, 8, 4), "AVI "); Check("RIFF 长度与文件一致", BitConverter.ToUInt32(data, 4) + 8, (uint)len); Check("hdrl 标识", Encoding.ASCII.GetString(data, 12, 4) + Encoding.ASCII.GetString(data, 20, 4), "LISThdrl"); Check("hdrl LIST 长度含 form type", BitConverter.ToUInt32(data, 16), 192u); Check("strl LIST 长度含 form type", BitConverter.ToUInt32(data, 92), 116u); Check("avih 块长 56", BitConverter.ToUInt32(data, 28), 56u); Check("已写总帧数", BitConverter.ToUInt32(data, 48), 3u); Check("stream 头部类型 vids", Encoding.ASCII.GetString(data, 108, 4), "vids"); Check("编码器 MJPG", Encoding.ASCII.GetString(data, 112, 4), "MJPG"); Check("stream 长度=3", BitConverter.ToUInt32(data, 140), 3u); Check("strf 压缩格式", Encoding.ASCII.GetString(data, 172 + 16, 4), "MJPG"); Check("宽度写对", BitConverter.ToInt32(data, 172 + 4), 64); Check("高度写对", BitConverter.ToInt32(data, 172 + 8), 48); Check("movi 标识", Encoding.ASCII.GetString(data, 212, 4) + Encoding.ASCII.GetString(data, 220, 4), "LISTmovi"); Check("第一帧块标识", Encoding.ASCII.GetString(data, 224, 4), "00dc"); // 把第一帧的 JPEG 抽出来,验证能解码成 64x48 int firstLen = (int)BitConverter.ToUInt32(data, 228); byte[] jpg = new byte[firstLen]; Array.Copy(data, 232, jpg, 0, firstLen); Check("JPEG 头 FFD8", jpg[0] == 0xFF && jpg[1] == 0xD8, true); using (MemoryStream ms = new MemoryStream(jpg)) using (Image img = Image.FromStream(ms)) { Check("解回的图宽度", img.Width, 64); Check("解回的图高度", img.Height, 48); } // idx1 在文件尾部 int idxPos = -1; for (int i = data.Length - 4; i >= 0; i--) { if (data[i] == 'i' && data[i + 1] == 'd' && data[i + 2] == 'x' && data[i + 3] == '1') { idxPos = i; break; } } Check("找到 idx1", idxPos > 0, true); Check("idx1 大小为 16*3", BitConverter.ToUInt32(data, idxPos + 4), 48u); Check("movi 长度接得上 idx1", 224 + BitConverter.ToUInt32(data, 216) - 4, (uint)idxPos); Check("idx1 每帧都是关键帧标记", BitConverter.ToUInt32(data, idxPos + 8 + 4), 0x10u); // 奇数长度帧的补齐:块总长必须是偶数 long moviLen = BitConverter.ToUInt32(data, 216); Check("movi 长度为偶数(块补齐生效)", moviLen % 2, 0u); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 异常:" + ex.Message + " @ " + ex.StackTrace.Split('\n')[0]); } _lines.Add("通过 " + _pass + " / " + (_pass + _fail)); string all = string.Join("\r\n", _lines.ToArray()) + "\r\n"; Console.WriteLine(all); try { Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "selftest-screenrec.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { // 真实录一小段(给发布前验收用):--rectest <输出文件> <秒数> static int RealRecord(string outFile, int seconds) { Rectangle r = SystemInformation.VirtualScreen; Size size = RecOps.ScaleSize(r.Width, r.Height, 0.5); int fps = 10; using (MjpegAviWriter w = new MjpegAviWriter(outFile, size.Width, size.Height, fps, 75)) { Stopwatch sw = Stopwatch.StartNew(); Stopwatch frameSw = new Stopwatch(); while (sw.Elapsed.TotalSeconds < seconds) { frameSw.Reset(); frameSw.Start(); using (Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) g.CopyFromScreen(r.X, r.Y, 0, 0, new Size(size.Width, size.Height), CopyPixelOperation.SourceCopy); w.AddFrame(bmp); } int wait = 1000 / fps - (int)frameSw.ElapsedMilliseconds; if (wait > 0) Thread.Sleep(wait); } w.Close(); Console.WriteLine("frames=" + w.FrameCount + " bytes=" + w.BytesWritten + " size=" + size.Width + "x" + size.Height); } return 0; } [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(RecSelfTest.Run(args.Length >= 2 ? args[1] : null)); } if (args != null && args.Length >= 3 && args[0] == "--rectest") { int sec = 3; int.TryParse(args[2], out sec); if (sec < 1) sec = 1; Environment.Exit(RealRecord(args[1], sec)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new RecForm()); } } }