Best FlaUI code snippet using FlaUI.Core.Capturing.VideoRecorder.Dispose
VideoRecorder.cs
Source:VideoRecorder.cs  
...131                    // Write the received frame and save it as last image132                    ffmpegIn.WriteAsync(img.Data, 0, img.Data.Length);133                    if (lastImage != null)134                    {135                        lastImage.Dispose();136                        lastImage = null;137                        GC.Collect();138                    }139                    lastImage = img;140                }141            }142            ffmpegIn.Flush();143            ffmpegIn.Close();144            ffmpegIn.Dispose();145            ffmpegProcess?.WaitForExit();146            ffmpegProcess?.Dispose();147        }148        /// <summary>149        /// Starts recording.150        /// </summary>151        private void Start()152        {153            _shouldRecord = true;154            _recordStartTime = DateTime.UtcNow;155            _recordTask = Task.Factory.StartNew(async () => await RecordLoop(), TaskCreationOptions.LongRunning);156            _writeTask = Task.Factory.StartNew(WriteLoop, TaskCreationOptions.LongRunning);157        }158        /// <summary>159        /// Stops recording and finishes the video file.160        /// </summary>161        public void Stop()162        {163            if (_recordTask != null)164            {165                _shouldRecord = false;166                _recordTask.Wait();167                _recordTask = null;168            }169            _frames.CompleteAdding();170            if (_writeTask != null)171            {172                try173                {174                    _writeTask.Wait();175                    _writeTask = null;176                }177                catch (Exception ex)178                {179                    Logger.Default.Warn(ex.Message, ex);180                }181            }182        }183        public void Dispose()184        {185            Stop();186        }187        private Process StartFFMpeg(string exePath, string arguments)188        {189            var process = new Process190            {191                StartInfo =192                    {193                        FileName = exePath,194                        Arguments = arguments,195                        UseShellExecute = false,196                        CreateNoWindow = true,197                        RedirectStandardError = true,198                        RedirectStandardInput = true,199                        RedirectStandardOutput = true,200                    },201                EnableRaisingEvents = true202            };203            process.OutputDataReceived += OnProcessDataReceived;204            process.ErrorDataReceived += OnProcessDataReceived;205            process.Start();206            if (_settings.EncodeWithLowPriority)207            {208                process.PriorityClass = ProcessPriorityClass.BelowNormal;209            }210            process.BeginErrorReadLine();211            return process;212        }213        private void OnProcessDataReceived(object s, DataReceivedEventArgs e)214        {215            if (!String.IsNullOrWhiteSpace(e.Data))216            {217                Logger.Default.Info(e.Data);218            }219        }220        private byte[] BitmapToByteArray(Bitmap bitmap)221        {222            using (var stream = new MemoryStream())223            {224                bitmap.Save(stream, _settings.UseCompressedImages ? ImageFormat.Png : ImageFormat.Bmp);225                return stream.ToArray();226            }227        }228        public static async Task<string> DownloadFFMpeg(string targetFolder)229        {230            var bits = Environment.Is64BitOperatingSystem ? 64 : 32;231            if (bits == 32)232            {233                throw new NotSupportedException("The current FFMPEG builds to not support 32-bit.");234            }235            var uri = new Uri($"https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip");236            var archivePath = Path.Combine(Path.GetTempPath(), "ffmpeg.zip");237            var destPath = Path.Combine(targetFolder, "ffmpeg.exe");238            if (!File.Exists(destPath))239            {240                // Download241                using (var webClient = new WebClient())242                {243                    await webClient.DownloadFileTaskAsync(uri, archivePath);244                }245                // Extract246                Directory.CreateDirectory(targetFolder);247                await Task.Run(() =>248                {249                    using (var archive = ZipFile.OpenRead(archivePath))250                    {251                        var exeEntry = archive.Entries.First(x => x.Name == "ffmpeg.exe");252                        exeEntry.ExtractToFile(destPath, true);253                    }254                });255                File.Delete(archivePath);256            }257            return destPath;258        }259        private class ImageData : IDisposable260        {261            public int Width { get; set; }262            public int Height { get; set; }263            public bool IsRepeatFrame { get; private set; }264            public byte[] Data { get; set; }265            public static readonly ImageData RepeatImage = new ImageData { IsRepeatFrame = true };266            public void Dispose()267            {268                Data = null;269            }270        }271    }272}273#endif...UiTestBase.cs
Source:UiTestBase.cs  
...106      EventListener = new DebugEventListener(process.StandardOutput);107      EventListener.Start();108      StartVideoRecorder();109    }110    public void Dispose()111    {112      CurrentInstance = null;113      TakeScreenShot(_testMethodName);114      EventListener?.Stop();115      CloseApplication();116      StopVideoRecorder();117      _automation?.Dispose();118      _automation = null;119    }120    private void CloseApplication()121    {122      _application?.Close();123  124      Retry.WhileFalse(125        () => _application?.HasExited ?? true,126        TimeSpan.FromSeconds(2),127        ignoreException: true128      );129  130      _application?.Dispose();131      _application = null;132    }133    private CaptureImage CaptureImage() => 134      Capture.Rectangle(135        new Rectangle136        {137          X = 0,138          Y = 0,139          Width = MainWindow.BoundingRectangle.Width,140          Height = MainWindow.BoundingRectangle.Height141        }142      );143    private void StartVideoRecorder()144    {145      // move window so it gets captured correctly146      MainWindow.Move(0, 0);147      SystemInfo.RefreshAll();148      var outputDirectory = Path.Combine(RecordingsOutputPath, SanitizeFileName(_testClassName));149      var outputPath = Path.Combine(outputDirectory, $"{SanitizeFileName(_testMethodName)}.mkv");150      _recorder = new VideoRecorder(151        new VideoRecorderSettings152        {153          VideoFormat = VideoFormat.x264,154          VideoQuality = 6,155          TargetVideoPath = outputPath,156          ffmpegPath = FfmpegPath157        },158        CaptureFrame159      );160      Directory.CreateDirectory(outputDirectory);161    }162    private CaptureImage CaptureFrame(VideoRecorder recorder)163    {164      var testName = $"{_testClassName}.{_testMethodName}";165      var img = CaptureImage();166      img.ApplyOverlays(167        new InfoOverlay(img)168        {169          RecordTimeSpan = recorder.RecordTimeSpan,170          OverlayStringFormat = testName171            + "\n{rt:hh\\:mm\\:ss\\.fff} | {name} | CPU: {cpu} | RAM: "172            + @"{mem.p.used}/{mem.p.tot} ({mem.p.used.perc})"173        },174        new MouseOverlay(img)175      );176      return img;177    }178    private void StopVideoRecorder()179    {180      _recorder?.Stop();181      _recorder?.Dispose();182      _recorder = null;183    }184    private void TakeScreenShot(string testName)185    {186      var outputDirectory = Path.Combine(ScreenshotsOutputPath, SanitizeFileName(_testClassName));187      var imageFilename = $"{SanitizeFileName(testName)}.png".Replace(@"\", string.Empty);188      var imagePath = Path.Combine(outputDirectory, imageFilename);189      try190      {191        Directory.CreateDirectory(outputDirectory);192        CaptureImage().ToFile(imagePath);193      }194      catch (Exception ex)195      {...CaptureTests.cs
Source:CaptureTests.cs  
...43                img.ApplyOverlays(new InfoOverlay(img) { RecordTimeSpan = r.RecordTimeSpan, OverlayStringFormat = @"{rt:hh\:mm\:ss\.fff} / {name} / CPU: {cpu} / RAM: {mem.p.used}/{mem.p.tot} ({mem.p.used.perc})" }, new MouseOverlay(img));44                return img;45            });46            System.Threading.Thread.Sleep(5000);47            recorder.Dispose();48        }49    }50}...Dispose
Using AI Code Generation
1using FlaUI.Core.Capturing;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8    {9        static void Main(string[] args)10        {11            using (var videoRecorder = new VideoRecorder())12            {13                videoRecorder.StartRecording();14                videoRecorder.StopRecording();15            }16        }17    }18}19using FlaUI.Core.Capturing;20using System;21using System.Collections.Generic;22using System.Linq;23using System.Text;24using System.Threading.Tasks;25{26    {27        static void Main(string[] args)28        {29            using (var videoRecorder = new VideoRecorder())30            {31                videoRecorder.StartRecording();32                videoRecorder.StopRecording();33            }34        }35    }36}37using FlaUI.Core.Capturing;38using System;39using System.Collections.Generic;40using System.Linq;41using System.Text;42using System.Threading.Tasks;43{44    {45        static void Main(string[] args)46        {47            using (var videoRecorder = new VideoRecorder())48            {49                videoRecorder.StartRecording();50                videoRecorder.StopRecording();51            }52        }53    }54}55using FlaUI.Core.Capturing;56using System;57using System.Collections.Generic;58using System.Linq;59using System.Text;60using System.Threading.Tasks;61{62    {63        static void Main(string[] args)64        {65            using (var videoRecorder = new VideoRecorder())66            {67                videoRecorder.StartRecording();68                videoRecorder.StopRecording();69            }70        }71    }72}73using FlaUI.Core.Capturing;74using System;75using System.Collections.Generic;76using System.Linq;77using System.Text;78using System.Threading.Tasks;79{80    {Dispose
Using AI Code Generation
1using FlaUI.Core;2using FlaUI.Core.Capturing;3using FlaUI.Core.Definitions;4using FlaUI.Core.Tools;5using FlaUI.UIA3;6using System;7using System.Collections.Generic;8using System.Diagnostics;9using System.Linq;10using System.Text;11using System.Threading.Tasks;12using System.Windows.Forms;13using FlaUI.Core.AutomationElements;14using FlaUI.Core.Input;15using FlaUI.Core.WindowsAPI;16using System.Threading;17{18    {19        private static AutomationBase automation;20        private static Application app;21        private static Window window;22        private static string path = @"C:\Users\Public\Videos\";23        private static string fileName = "test";24        private static string fileExtension = ".avi";25        private static string filePath = path + fileName + fileExtension;26        static void Main(string[] args)27        {28            automation = new UIA3Automation();29            app = FlaUI.Core.Application.Launch(@"C:\Windows\System32\notepad.exe");30            window = app.GetMainWindow(automation);31            window.WaitUntilResponsive();32            VideoRecorder videoRecorder = new VideoRecorder(filePath, 30);33            videoRecorder.Start();34            Thread.Sleep(2000);35            window.Close();36            videoRecorder.Stop();37            videoRecorder.Dispose();38            System.Diagnostics.Process.Start("explorer.exe", path);39        }40    }41}Dispose
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using FlaUI.Core.Capturing;7using System.IO;8{9    {10        static void Main(string[] args)11        {12            VideoRecorder recorder = new VideoRecorder();13            recorder.StartRecording("C:\\Users\\Public\\Videos\\TestVideo.mp4");14            recorder.StopRecording();15            recorder.Dispose();16        }17    }18}Dispose
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using System.IO;7using FlaUI.Core.Capturing;8using FlaUI.Core;9using FlaUI.Core.Definitions;10using FlaUI.Core.Input;11using FlaUI.Core.WindowsAPI;12using FlaUI.Core.Tools;13using FlaUI.Core.AutomationElements;Dispose
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using FlaUI.Core;5using FlaUI.Core.Capturing;6using FlaUI.Core.Conditions;7using FlaUI.Core.Definitions;8using FlaUI.Core.Input;9using FlaUI.Core.WindowsAPI;10using FlaUI.UIA3;11using System.Drawing;12using System.Drawing.Imaging;13using System.Collections.Generic;14using System.Linq;15using System.Text;16using System.Threading;17using System.Diagnostics;18{19    {20        static void Main(string[] args)21        {22            var process = Process.Start(@"C:\Windows\System32\calc.exe");23            var automation = new UIA3Automation();24            var mainWindow = automation.GetDesktop().FindFirstChild(cf => cf.ByProcessId(process.Id)).AsWindow();25            mainWindow.WaitUntilResponsive();26            var calculatorButton = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("num8Button"));27            calculatorButton.Click();28            var calculatorButton1 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("num9Button"));29            calculatorButton1.Click();30            var calculatorButton2 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("multiplyButton"));31            calculatorButton2.Click();32            var calculatorButton3 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("num8Button"));33            calculatorButton3.Click();34            var calculatorButton4 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("equalButton"));35            calculatorButton4.Click();36            var calculatorButton5 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("num9Button"));37            calculatorButton5.Click();38            var calculatorButton6 = mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("minusButton"));39            calculatorButton6.Click();Dispose
Using AI Code Generation
1using System;2using System.IO;3using System.Threading;4using FlaUI.Core.Capturing;5using FlaUI.Core.Definitions;6using FlaUI.Core.Input;7using FlaUI.Core.Tools;8using FlaUI.UIA3;9{10    {11        static void Main(string[] args)12        {13            var app = FlaUI.Core.Application.Launch(@"C:\Windows\System32\calc.exe");14            var automation = new UIA3Automation();15            var mainWindow = app.GetMainWindow(automation);16            using (var videoRecorder = new FlaUI.Core.Capturing.VideoRecorder())17            {18                videoRecorder.StartRecording();19                Keyboard.TypeSimultaneously(VirtualKeyShort.ALT, VirtualKeyShort.F4);20                Thread.Sleep(2000);Dispose
Using AI Code Generation
1using FlaUI.Core.Capturing;2using System;3{4    {5        static void Main(string[] args)6        {7            using (var videoRecorder = new VideoRecorder())8            {9                videoRecorder.StartRecording();10                Console.WriteLine("Press any key to stop recording");11                Console.ReadKey();12                videoRecorder.StopRecording();13                videoRecorder.Save("Video.flv");14            }15        }16    }17}18videoRecorder.Save("Video.flv", true);19videoRecorder.Save("Video.mp4", true, true);20videoRecorder.Save("Video.mp4", true, true, 60);21videoRecorder.Save("Video.mp4", true, true, 60, new System.Drawing.Size(1920, 1080));22videoRecorder.Save("Video.mp4", true, true, 60, new System.Drawing.Size(1920, 1080), 100);Dispose
Using AI Code Generation
1using System;2using System.IO;3using FlaUI.Core.Capturing;4using FlaUI.Core.Definitions;5using FlaUI.Core.UITests;6using FlaUI.Core.UITests.TestFramework;7using NUnit.Framework;8{9    {10        public void TestVideoRecorder()11        {12            var recorder = new VideoRecorder();13            recorder.StartRecording();14            var window = Application.GetMainWindow(Automation);15            var button = window.FindFirstDescendant(cf => cf.ByAutomationId("Button")).AsButton();16            button.Click();17            recorder.StopRecording();18            recorder.Dispose();19        }20    }21}22using System;23using System.IO;24using FlaUI.Core.Capturing;25using FlaUI.Core.Definitions;26using FlaUI.Core.UITests;27using FlaUI.Core.UITests.TestFramework;28using NUnit.Framework;29{30    {31        public void TestVideoRecorder()32        {33            var recorder = new VideoRecorder();34            recorder.StartRecording();35            var window = Application.GetMainWindow(Automation);36            var button = window.FindFirstDescendant(cf => cf.ByAutomationId("Button")).AsButton();37            button.Click();38            recorder.StopRecording();39            recorder.Dispose();40        }41    }42}43using System;44using System.IO;45using FlaUI.Core.Capturing;46using FlaUI.Core.Definitions;47using FlaUI.Core.UITests;48using FlaUI.Core.UITests.TestFramework;49using NUnit.Framework;50{51    {52        public void TestVideoRecorder()53        {54            var recorder = new VideoRecorder();55            recorder.StartRecording();56            var window = Application.GetMainWindow(Automation);57            var button = window.FindFirstDescendant(cf => cf.ByAutomationId("Button")).AsButton();58            button.Click();59            recorder.StopRecording();60            recorder.Dispose();61        }62    }63}Dispose
Using AI Code Generation
1using System;2using System.IO;3using FlaUI.Core.Capturing;4using FlaUI.Core.Definitions;5using FlaUI.Core.Tools;6using FlaUI.UIA3;7{8    {9        static void Main(string[] args)10        {11            var application = FlaUI.Core.Application.Launch(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");12            var automation = new UIA3Automation();13            var window = application.GetMainWindow(automation);14            var videoRecorder = new VideoRecorder(window, Path.Combine(Directory.GetCurrentDirectory(), "video1.mp4"));15            videoRecorder.StartRecording();16            window.Resize(1000, 1000);17            window.Resize(2000, 2000);18            videoRecorder.StopRecording();19            videoRecorder.Dispose();20            Console.WriteLine("Press any key to close");21            Console.ReadKey();22        }23    }24}Dispose
Using AI Code Generation
1using System;2using System.IO;3using FlaUI.Core.Capturing;4{5    {6        static void Main(string[] args)7        {8            using (var videoRecorder = new VideoRecorder())9            {10                videoRecorder.Start();11                videoRecorder.Stop();12                videoRecorder.Save("video.avi");13            }14            Console.WriteLine("Press any key to exit");15            Console.ReadKey();16        }17    }18}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
