Search code examples
c#wpfvideodesktopaforge

Capture desktop with Aforge


I have seen various tutorial like this on how to make a video from webcam, show and record it. What I would like now is to be able to do the same with the desktop so that I can cross-reference the computer activity with the external world. So what I would like is to be able to record a video of what happens on the computer possibly usig AForge. I found no reference about that, is it therefore impossible to do with Aforge?

--ADD--

I have implemented the proposed solution as below: enter image description here

Thanks

but when I look at the png is all black. The saving procedure is correct for when I save the webcam frame it is ok. Could you please tell me what is wrong in my adaptation from your code?

Thanks


Solution

  • It may not be a professionally solution and not realtime but it does the work for simple scenarios like yours. It is a console application built with Net Framework 4.7.2. And I rebuilt the assembly Aforge.Video.FFMPEG by using its source code so that it can be used with Net Framework 4.0+.

    using AForge.Video.FFMPEG;
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;
    
    class Program
        {
            static VideoFileWriter VideoFileWriter;
            static Stopwatch stopwatch = new Stopwatch();
            static void Main(string[] args)
            {
                VideoFileWriter = new VideoFileWriter();
    
                Size screenSize = Screen.PrimaryScreen.Bounds.Size;
                VideoFileWriter.Open("test.mp4", screenSize.Width, screenSize.Height, 30, VideoCodec.MPEG4, 19200000);
                Bitmap bitmap = new Bitmap(screenSize.Width, screenSize.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(bitmap);
                stopwatch.Start();
                while (stopwatch.Elapsed < TimeSpan.FromSeconds(10)) // Record for ten seconds.
                {
                    g.CopyFromScreen(0, 0, 0, 0, screenSize, CopyPixelOperation.SourceCopy);
                    VideoFileWriter.WriteVideoFrame(bitmap, stopwatch.Elapsed);
                    Thread.Sleep(29);
                }
                VideoFileWriter.Close();
                g.Dispose();
            }
        }