Thursday, May 6, 2010

Capture the screen activity and save as a video file in C#

There are some software you may find to capture the screen as a video file. For example camstudio, etc. Here a piece of code written in C# to capture the screen activity and save as a video file in specified location. It is very useful in some control application to watch the controllers’ activity for later requirements.

To run this program you have to install windows media encoder 9 series. Windows media encoder is freely available media encoder developed by Microsoft which enables the developer to capture screen activities. You can download windows media encoder 9 here.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WMEncoderLib;
using WMPLib;
using System.Threading;


namespace WindowsFormsApplication1
{


public partial class Form1 : Form
{

private WMEncoder m_encoder;
private IWMEncProfile m_profile;



public Form1()
{
InitializeComponent();
}


private void startCapture(string targetFileName)
{
m_encoder = new WMEncoderClass();


IWMEncSourceGroup SrcGrp;
IWMEncSourceGroupCollection SrcGrpColl;
SrcGrpColl = m_encoder.SourceGroupCollection;
SrcGrp = SrcGrpColl.Add("sourceGroupName");

IWMEncSource SrcVid = null;
IWMEncSource SrcAud = null;

SrcVid = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
SrcVid.SetInput("screenCap://screenCapture1", "", "");

SrcAud = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
SrcAud.SetInput("Device://Default_Audio_Device", "", "");

IWMEncProfileCollection ProColl = m_encoder.ProfileCollection;
int ILength = ProColl.Count;
string name;
for (int i = 0; i <= (ILength - 1); i++)
{
name = ProColl.Item(i).Name;
m_profile = ProColl.Item(i);

}


SrcGrp.set_Profile(m_profile);

IWMEncDisplayInfo Descr;
Descr = m_encoder.DisplayInfo;
Descr.Author = "mohamed";
Descr.Copyright = "copyright";
Descr.Description = "desccription";
Descr.Rating = "rating";
Descr.Title = "my title";

IWMEncAttributes Attr;
Attr = m_encoder.Attributes;
Attr.Add("URL", "www.google.com");

IWMEncFile File;
File = m_encoder.File;
File.LocalFileName = targetFileName;

if (null != SrcVid)
{
((IWMEncVideoSource)SrcVid).CroppingBottomMargin = 1;
((IWMEncVideoSource)SrcVid).CroppingTopMargin = 1;
((IWMEncVideoSource)SrcVid).CroppingLeftMargin = 1;
((IWMEncVideoSource)SrcVid).CroppingRightMargin = 1;
}

try
{
m_encoder.Start();
}
catch (Exception ex)
{
MessageBox.Show("could not capture " + ex.Message);

}
}

}
}

Add WMEncoderLib to the reference. Call the method startCapture and pass the location to save the video file.
Ex: Form1 f = new Form1();
f.startCapture("C:/Users/MOHAMED/Desktop/az.wmv");

1 comment:

  1. can you sen me the source code in niyomal.study@gmail.com thak you

    ReplyDelete