HI WELCOME TO KANSIRIS

Capture screen activities/video using WmEncoder

Leave a Comment

Today is the time for a small utility which will allow you to capture your screen activities in a video file in WMV format. You can play that video file later in any video player later or use it for some kind of presentations etc. The following program captures the full desktop but there are ways to capture a specific window handle too. This is just a demonstration of the many possibilities with WmEncoder interface that comes with windows media encoder. If you are running vista you will also have to download the patch for encoder on vista..... If you need just the executable file and don't want to bother about the code and programming aspects... just leave your comment here with your e-mail. I will send you the exe and required files. For developers and programmers ..here you go..


Here are some of the screenshots of how it will appearar in your system tray...when YOU launch it... 






















1 // Copyright © Yours truly. All rights reserved.
2
3 // To use this code, you must have downloaded windows media encoder from
4 // http://www.microsoft.com/downloads/details.aspx?familyid=5691BA02-E496-465A-BBA9-B2F1182CDF24&displaylang=en
5 // and added COM reference to WMEncoderLib after installing the Windows Media
6 // Encoder.
7 // Also, if you are going to use this capturevideo on Windows Vista, please
8 // also download the vista patch before you use it so as to avoid memory crash
9 // of the application : http://support.microsoft.com/kb/929182.
10 // Follow the details in KB929182 to uninstall KB954156 patch if you've already
11 // installed the KB954156 patch.The patch path for x86 vista machine (32bit) is :
12 // http://download.microsoft.com/download/0/3/d/03d35c05-67da-40e0-9e45-3ea0ca6329a4/windowsmedia9-kb929182-intl.exe.
13
14
15 using System;
16 using System.Diagnostics;
17 using System.IO;
18 using System.Windows.Forms;
19
20 using WMEncoderLib;
21
22 namespace CaptureScreenVideo
23 {
24 // *************************************************************************
25 /// <summary>
26 /// Test class to demonstrate the video capture using windows media encoder.
27 /// </summary>
28 class Program
29 {
30 // *********************************************************************
31 /// <summary>
32 /// The main entry point for the program.
33 /// </summary>
34 /// <param name="args">The command line arguments.</param>
35 [STAThread]
36 static void Main(string[] args)
37 {
38 MyEncoder enc = new MyEncoder();
39 enc.Size = new System.Drawing.Size(1, 1);
40 Application.Run(enc);
41 }
42
43 } // end class Program
44
45 // *************************************************************************
46 /// <summary>
47 /// The form class used to show the notify icon and tray menus.
48 /// </summary>
49 /// <remarks>
50 /// <para>The class assumes you have a resources file included in the
51 /// project and their names are Started.ico,Paused.ico,Stopped.ico.
52 /// </para>
53 /// </remarks>
54 public class MyEncoder:Form
55 {
56 // *********************************************************************
57 /// <summary>
58 /// An enum for the notify icon menu options.
59 /// </summary>
60 private enum MainMenuIndex
61 {
62 /// <summary>Start capture menu </summary>
63 Start = 0,
64 /// <summary>Profiles menu </summary>
65 Profiles,
66 /// <summary>Pause capture menu </summary>
67 Pause,
68 /// <summary>Stop capture menu </summary>
69 Stop,
70 /// <summary>Download library from Microsoft menu </summary>
71 Download,
72 /// <summary>Exit menu </summary>
73 Exit
74 }
75
76 // *********************************************************************
77 /// <summary>
78 /// An enum for the notify icon profile menu options.
79 /// </summary>
80 private enum ProfileMenuIndex
81 {
82 /// <summary>Profiles->Audio only menu </summary>
83 AudioOnly = 0,
84 /// <summary>Profiles->Video only menu </summary>
85 VideoOnly = 1,
86 /// <summary>Profiles->Audio/Video only menu </summary>
87 AudioVideo = 2
88 }
89
90 // *********************************************************************
91 /// <summary>
92 /// An enum for the video capture states.
93 /// </summary>
94 private enum CaptureState
95 {
96 /// <summary>Capture is stopped.</summary>
97 Stopped = 0,
98 /// <summary>Capture is started.</summary>
99 Started = 1,
100 /// <summary>Capture is paused.</summary>
101 Paused = 2
102 }
103
104 private WMEncoder m_encoder;
105 private NotifyIcon m_ntfy;
106 private IWMEncProfile m_profile;
107 private CaptureState m_status;
108 private SaveFileDialog m_saveFile;
109
110 // *********************************************************************
111 /// <summary>
112 /// Initializes a new instance of <see cref="MyEncoder"/>.
113 /// </summary>
114 /// <remarks>
115 /// <para>
116 /// This also creates the notify icon menu items and shows the baloon
117 /// tooltip at startup.
118 /// </para>
119 /// </remarks>
120 public MyEncoder()
121 {
122 // Create the notify icon instance.
123 m_ntfy = new NotifyIcon();
124
125 // Create the context menu to show ehn user right clicks on system
126 // tray icon.
127 ContextMenu mnu = new ContextMenu();
128 MenuItem startItem = new MenuItem("Start Capture", HandleStart);
129 MenuItem profileMnu = new MenuItem("Profiles/Video quality");
130 MenuItem pauseItem = new MenuItem("Pause Capture", HandlePause);
131 MenuItem stopItem = new MenuItem("Stop Capture", HandleStop);
132 MenuItem downLoad = new MenuItem("Download Microsoft Library...",
133 HandleDownload);
134 stopItem.Enabled = pauseItem.Enabled = false;
135 MenuItem exitItem = new MenuItem("Exit", HandleExit);
136 mnu.MenuItems.AddRange(
137 new MenuItem[] { startItem, profileMnu, pauseItem, stopItem,
138 downLoad, exitItem });
139
140 // assign the menu to notify icon
141 m_ntfy.ContextMenu = mnu;
142 m_ntfy.BalloonTipText = "Right click to view capture options";
143 m_ntfy.BalloonTipTitle = "Capture screen video";
144 m_ntfy.Visible = true;
145 m_ntfy.Icon = Resource.Stopped;
146 m_ntfy.Text = "Click to start capturing.";
147 m_ntfy.Click += new EventHandler(NotifyIcon_Click);
148 m_ntfy.DoubleClick += new EventHandler(NotifyIcon_DoubleClick);
149 m_ntfy.ShowBalloonTip(2000);
150 } // end ctor.
151
152 // *********************************************************************
153 /// <summary>
154 /// Handles the notify icon's double click.
155 /// </summary>
156 /// <param name="sender">The object that started the event.</param>
157 /// <param name="e">An <see cref="EventArgs"/> that contains the event
158 /// data.</param>
159 private void NotifyIcon_DoubleClick(object sender, EventArgs e)
160 {
161 // stop if started or paused
162 if (m_status == CaptureState.Started ||
163 m_status == CaptureState.Paused)
164 {
165 HandleStop(sender, e);
166 }
167 }
168
169 // *********************************************************************
170 /// <summary>
171 /// Handles the notify icon's click and starts/pauses/stops the capture.
172 /// </summary>
173 /// <param name="sender">The object that started the event.</param>
174 /// <param name="e">An <see cref="EventArgs"/> that contains the event
175 /// data.</param>
176 private void NotifyIcon_Click(object sender, EventArgs e)
177 {
178 MouseEventArgs mse = e as MouseEventArgs;
179 if (mse != null && mse.Button == MouseButtons.Right) return;
180 switch (m_status)
181 {
182 case CaptureState.Started:
183 case CaptureState.Paused:
184 HandlePause(m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Pause], e);
185 break;
186 case CaptureState.Stopped:
187 HandleStart(sender, e);
188 break;
189 }
190 }
191
192 // *********************************************************************
193 /// <summary>
194 /// Raises the System.Windows.Forms.Form.Shown event.Hides the main
195 /// window and and creats available profiles from your machine (you will
196 /// have these ready-made profiles only after you installed the
197 /// WMEncoder library from Microsoft site) into various categories.
198 /// </summary>
199 /// <param name="e">An <see cref="EventArgs"/> that contains the event
200 /// data.</param>
201 protected override void OnShown(EventArgs e)
202 {
203 base.OnShown(e);
204 try
205 {
206 this.Hide();
207 // Create a WMEncoder object.
208 m_encoder = new WMEncoderClass();
209 IWMEncProfileCollection ProColl = m_encoder.ProfileCollection;
210 int lLength = ProColl.Count;
211 string name;
212 string currProfile = "Screen Video/Audio High (CBR)";
213 MenuItem item;
214 MenuItem profileMnu = m_ntfy.ContextMenu.MenuItems[(int)MainMenuIndex.Profiles];
215 MenuItem audioOnly = new MenuItem("Audio only");
216 MenuItem videoOnly = new MenuItem("Video only");
217 MenuItem audioVideo = new MenuItem("Audio/Video");
218 profileMnu.MenuItems.AddRange(new MenuItem[] { audioOnly,videoOnly,audioVideo });
219 for (int i = 0; i <= (lLength - 1); i++)
220 {
221 name = ProColl.Item(i).Name;
222 if (name.ToUpper().IndexOf("VIDEO") >= 0 &&
223 name.ToUpper().IndexOf("AUDIO") >= 0)
224 {
225 item = audioVideo.MenuItems.Add(name,HandleProfileChanged);
226 item.Tag = i;
227 if (name.Equals(currProfile))
228 {
229 item.Checked = true;
230 m_profile = ProColl.Item(i);
231 }
232 }
233 else if (name.ToUpper().IndexOf("VIDEO") >= 0 &&
234 name.ToUpper().IndexOf("AUDIO") < 0)
235 {
236 item = videoOnly.MenuItems.Add(name,HandleProfileChanged);
237 item.Tag = i;
238 }
239 else if (name.ToUpper().IndexOf("VIDEO") < 0 &&
240 name.ToUpper().IndexOf("AUDIO") >= 0)
241 {
242 item = audioOnly.MenuItems.Add(name,HandleProfileChanged);
243 item.Tag = i;
244 }
245 }
246 }
247 catch (Exception ex)
248 {
249 MessageBox.Show(ex.ToString());
250 }
251 } // end OnShown
252
253 // *********************************************************************
254 /// <summary>
255 /// Starts capturing the video after taking the output video file from
256 /// user.The file type is decide based on what kind of capture is being
257 /// done which is based on the selected capture profile.
258 /// </summary>
259 public bool Start()
260 {
261 bool status = false;
262 if (m_saveFile == null)
263 {
264 m_saveFile = new SaveFileDialog();
265 }
266 // check the tag just so we do not show multiple Save file dialogs.
267 if (m_saveFile.Tag != null && (int)m_saveFile.Tag ==1) return false;
268 if (m_profile.Name.ToUpper().IndexOf("VIDEO") >= 0)
269 {
270 m_saveFile.Filter = "Windows Media Video (WMV)|*.wmv";
271 }
272 else
273 {
274 m_saveFile.Filter = "Windows Media Audio (WMA)|*.wma";
275 }
276 m_saveFile.FilterIndex = 0;
277 m_saveFile.CheckFileExists = false;
278 m_saveFile.CheckPathExists = true;
279 m_saveFile.Tag = 1;
280 try
281 {
282 if (m_saveFile.ShowDialog(this) == DialogResult.OK &&
283 !string.IsNullOrEmpty(m_saveFile.FileName))
284 {
285 this.StartCapture(m_saveFile.FileName);
286 status = true;
287 }
288 }
289 catch
290 {
291 // do some error handling here?
292 }
293 finally
294 {
295 m_saveFile.Tag = 0;
296 }
297 return status;
298 } // end start
299
300 // *********************************************************************
301 /// <summary>
302 /// Handles the "Start" menu click of context menu.
303 /// </summary>
304 /// <param name="source">The object that started the event.</param>
305 /// <param name="e">An <see cref="EventArgs"/> that contains the event
306 /// data.</param>
307 private void HandleStart(object source, EventArgs e)
308 {
309 if (this.Start())
310 {
311 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Start].Enabled =
312 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Profiles].Enabled =
313 false;
314 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Stop].Enabled =
315 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Pause].Enabled =
316 true;
317 m_ntfy.Icon = Resource.Started;
318 m_status = CaptureState.Started;
319 m_ntfy.Text = "Click to pause capturing or double click to stop.";
320 }
321 } // end HandleStart
322
323 // *********************************************************************
324 /// <summary>
325 /// Handles the "Pause/Resume" menu click of context menu.
326 /// </summary>
327 /// <param name="source">The object that started the event.</param>
328 /// <param name="e">An <see cref="EventArgs"/> that contains the event
329 /// data.</param>
330 private void HandlePause(object source, EventArgs e)
331 {
332 MenuItem item = (MenuItem) source;
333 if (null != item)
334 {
335 if (item.Text.ToUpper().Equals("PAUSE CAPTURE"))
336 {
337 item.Text = "Resume Capture";
338 m_encoder.Pause();
339 m_status = CaptureState.Paused;
340 m_ntfy.Text = "Click to resume capturing or double click to stop.";
341 m_ntfy.Icon = Resource.Paused;
342 }
343 else
344 {
345 item.Text = "Pause Capture";
346 m_encoder.Start();
347 m_status = CaptureState.Started;
348 m_ntfy.Icon = Resource.Started;
349 m_ntfy.Text = "Click to pause capturing or double click to stop.";
350 }
351 }
352 } // end HandlePause
353
354 // *********************************************************************
355 /// <summary>
356 /// Handles the "Stop" menu click of context menu.
357 /// </summary>
358 /// <param name="source">The object that started the event.</param>
359 /// <param name="e">An <see cref="EventArgs"/> that contains the event
360 /// data.</param>
361 private void HandleStop(object source, EventArgs e)
362 {
363 this.Stop();
364 // Enable the Start menu
365 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Start].Enabled =
366 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Profiles].Enabled = true;
367 // Disable the Stop menu
368 m_ntfy.ContextMenu.MenuItems[(int)MainMenuIndex.Stop].Enabled =
369 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Pause].Enabled =
370 false;
371 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Pause].Text = "Pause Capture";
372 m_ntfy.Icon = Resource.Stopped;
373 m_status = CaptureState.Stopped;
374 m_ntfy.Text = "Click to start capturing.";
375 }
376
377 // *********************************************************************
378 /// <summary>
379 /// Handles the "Download Microsoft library" menu click of context menu.
380 /// </summary>
381 /// <param name="source">The object that started the event.</param>
382 /// <param name="e">An <see cref="EventArgs"/> that contains the event
383 /// data.</param>
384 private void HandleDownload(object source, EventArgs e)
385 {
386 Process.Start("http://www.microsoft.com/downloads/details.aspx?familyid=5691BA02-E496-465A-BBA9-B2F1182CDF24&displaylang=en");
387 if (Environment.OSVersion.Version.Major > 5)
388 {
389 MessageBox.Show("Please check http://support.microsoft.com/kb/929182 also!",
390 ""MessageBoxButtons.OK, MessageBoxIcon.Information);
391 }
392 }
393
394 // *********************************************************************
395 /// <summary>
396 /// Handles the "Profile" menu click of context menu.
397 /// </summary>
398 /// <param name="source">The object that started the event.</param>
399 /// <param name="e">An <see cref="EventArgs"/> that contains the event
400 /// data.</param>
401 private void HandleProfileChanged(object source, EventArgs e)
402 {
403 MenuItem item = (MenuItem) source;
404 if (null != source)
405 {
406 MenuItem mainMenu =
407 m_ntfy.ContextMenu.MenuItems[(intMainMenuIndex.Profiles];
408 foreach (MenuItem mnu in
409 mainMenu.MenuItems[(int)ProfileMenuIndex.AudioOnly].MenuItems)
410 {
411 mnu.Checked = false;
412 }
413 foreach (MenuItem mnu in
414 mainMenu.MenuItems[(intProfileMenuIndex.VideoOnly].MenuItems)
415 {
416 mnu.Checked = false;
417 }
418 foreach (MenuItem mnu in
419 mainMenu.MenuItems[(intProfileMenuIndex.AudioVideo].MenuItems)
420 {
421 mnu.Checked = false;
422 }
423 item.Checked = true;
424 m_profile = m_encoder.ProfileCollection.Item((int)item.Tag);
425 }
426 } // end HandleProfileChanged
427
428 // *********************************************************************
429 /// <summary>
430 /// Handles the "Exit" menu click of context menu.
431 /// </summary>
432 /// <param name="source">The object that started the event.</param>
433 /// <param name="e">An <see cref="EventArgs"/> that contains the event
434 /// data.</param>
435 private void HandleExit(object source, EventArgs e)
436 {
437 Stop();
438 m_ntfy.Dispose();
439 m_ntfy = null;
440 m_encoder = null;
441 Application.Exit();
442 }
443
444 // *********************************************************************
445 /// <summary>
446 /// Starts capturing the video into specified output video file from
447 /// user.
448 /// </summary>
449 /// <param name="targetFile">The video file where video is to be saved.
450 /// </param>
451 private void StartCapture(string targetFile)
452 {
453 if (m_encoder == null) m_encoder = new WMEncoderClass();
454 // Retrieve the source group collection and add a source group.
455 IWMEncSourceGroup SrcGrp;
456 IWMEncSourceGroupCollection SrcGrpColl;
457 SrcGrpColl = m_encoder.SourceGroupCollection;
458 SrcGrp = SrcGrpColl.Add("SourceGroupName");
459 // Add a video and audio source to the source group.
460 IWMEncSource SrcVid = null;
461 IWMEncSource SrcAud = null;
462 if (m_profile.Name.ToUpper().IndexOf("VIDEO") >= 0)
463 {
464 SrcVid = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
465 // Identify the source files to encode.
466 SrcVid.SetInput("ScreenCap://ScreenCapture1""""");
467 }
468 if (m_profile.Name.ToUpper().IndexOf("AUDIO") >= 0)
469 {
470 SrcAud = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
471 // Identify the source files to encode.
472 SrcAud.SetInput("Device://Default_Audio_Device""""");
473 }
474
475 SrcGrp.set_Profile (m_profile);
476
477 // Fill in the description object members.
478 IWMEncDisplayInfo Descr;
479 Descr = m_encoder.DisplayInfo;
480 Descr.Author = "Yours Truly";
481 Descr.Copyright = "Copyright © Yours truly";
482 Descr.Description = "Text description of encoded video/audio content:"
483 + targetFile;
484 Descr.Rating = "Video Rating information for " + targetFile;
485 Descr.Title = "Title of encoded video/audio content for " + targetFile;
486
487 IWMEncAttributes Attr;
488 Attr = m_encoder.Attributes;
489 Attr.Add("URL""www.mycomponent.blogspot.com");
490 // Specify a file object in which to save encoded content.
491 IWMEncFile File;
492 File = m_encoder.File;
493 File.LocalFileName = targetFile;
494 if (null != SrcVid)
495 {
496 ((IWMEncVideoSource) SrcVid).CroppingBottomMargin = 0;
497 ((IWMEncVideoSource) SrcVid).CroppingTopMargin = 0;
498 ((IWMEncVideoSource) SrcVid).CroppingLeftMargin = 0;
499 ((IWMEncVideoSource) SrcVid).CroppingRightMargin = 0;
500 }
501 try
502 {
503 // Start the encoding process.
504 m_encoder.Start();
505 }
506 catch(Exception ex)
507 {
508 MessageBox.Show("Could not start capturing! Try again.Error was:" + ex.Message,
509 "Error"MessageBoxButtons.OK, MessageBoxIcon.Warning);
510 }
511 } // end StartCapture
512
513 // *********************************************************************
514 /// <summary>
515 /// Stops capturing the video if already started.
516 /// </summary>
517 public void Stop()
518 {
519 if (m_encoder != null)
520 {
521 if (m_encoder.RunState != WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED)
522 {
523 m_encoder.Stop();
524 }
525 }
526 m_encoder = null;
527 GC.Collect(); // Important for Vista users.
528 } // end Stop
529
530 } // end class MyEncoder
531 } // end namespace CaptureScreenVideo

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.