Tuesday, August 31, 2010

Play Youtube Video Using C#

To play Youtube videos in C#, we use the Windows Media Player Control, as already in the post play mp3 - files.
The control can be added to the toolbox, by right clicking  on it and then selecting "Select Element ...". In the upcoming window switch to COM controls and then select Windows Media Player.
The multimedia file which is to be played can be set via the property URL. Now one can just put the address of the Youtube video as URL and the media player plays the video on the C# form. But the direct path to the video and not the URL address, on which the video is viewed online, has to be used.
Instead the infix "watch?v=" "/v/" thus has to be used, which describes the folder, in which the Youtube videos are palced. Furthermore, in the video Embedding may not be activated.

An example:

In the brower a video is viewable through the link "http://www.youtube.com/watch?v=8EbtaLNHluE", but the control needs the link "http://www.youtube.com/v/8EbtaLNHluE".
The following code then loads the video in the media player, the video then can be started by clicking "Play" in the video window:

axWindowsMediaPlayer1.URL = "http://www.youtube.com/v/8EbtaLNHluE";

The following example function changes the URL automatically, meaning she gets the online link as input and then plays it:

private void PlayVideo(string url)
{
    axWindowsMediaPlayer1.URL = url.Replace("watch?v=""/v/");
}

Monday, August 30, 2010

Include and Use VLC Player in C#

In this post I will show how to use the VLC Player in C#. This is in my opinion the best open source media player, so we can use it to play any audio or video files in our C# application.
For the VLC Player there exists an ActiveX component, which comes by as a .dll file.
So when downloading VLC, it is important to check the point "ActiveX component" (by default, this is anyway activated though).
Now an ActiveX control is installed during installation and registered on the computer. This control now can already be included in .Net. For that right click on the toolbox, select Add Elements, which prompts a windows to add new controls to open. We now switch to the tab COM controls and activate there VideoLAN VLC ActiveX Plugin v1.
If this entry is not availabe, the .dll file has to be registered manually, the right file is axvlc.dll in the VideoLAN folder.
ActiveX controls can be registered via regsvr32. Suppose the .dll file sits in C:\Program Files (x86)\VideoLAN\VLC\axvlc.dll. Then we can register it with executing regsvr32 "C:\Program Files (x86)\VideoLAN\VLC\axvlc.dll".
If the VLC control was successfully added to the toolbox, it can be added like any other to the form.

To play an arbitrary video or audiofile, the multimedia object first has to be added to Playlist, which we do with the function addTarget(). This expects 4 parameters, the first one describes the path to the object to be played. As second parameter play options can be set (as for example the width-to-height ratio). The third parameter is the playing mode and the fourth the position in the current playlist.
To play the file finally, the function play() has to be called.
pause() stops the playing, with a repeated call of play() the video / audiofile is continued from the same time.
The volume of the audio signal can be set by the parameter Volume, here 0 is no sound, 100 full volume.
The following example plays the video "Matrix" on my desktop with 50% volume.
addTarget() does not get any options, the playing mode should be self explainining and -666 as last parameter identifies the last position in the playlist.
Attention: In newer versions of the VLC player one has to append a "file:///" in front of the file path, otherwise the file does not play!

axVLCPlugin1.Volume = 50;
axVLCPlugin1.addTarget(@"C:\Users\User\Desktop\matrix.mp4"null, AXVLC.VLCPlaylistMode.VLCPlayListAppendAndGo, -666);
axVLCPlugin1.play();


Edit About this post I created a little video on youtube (in German): http://www.youtube.com/watch?v=Bh4qsHrk910

Sunday, August 29, 2010

Determine Color Depth

In C# we can read-out the color depth. This is set for every monitor, so first the desired screen has to be selected. For example Screen.PrimaryScreen denotes the primary screen, with Screen.AllScreens[Nr] Monitor [Nr] can be chosen.
The color depth is saved in the property BitsPerPixel, as the color depth says, by how many bits per pixel the color is described. There is 16 and 32 bit, nowaways nearly all computers use 32 bit:
The following command detects the color size of the primary screen:

int ColorDepth = Screen.PrimaryScreen.BitsPerPixel;

Saturday, August 28, 2010

Detect Number of Connected Monitors

In the .Net framework all to the computer connected screens are saved in the array Screen.AllScreens.
By the property Lenght this can of course be read-out, so in C# the following command determines the number of connected monitors:

int NrOfScreens = Screen.AllScreens.Length;

Friday, August 27, 2010

Open Standard Email Program

In the previous post I showed, how to open an URL with the standard browser. Today's post is about opening an email draft with the standard email client.
Again, System.Diagnostics.Process.Start() gives us the desired success. This time, a "mailto:" has to be put in front of the parameter, just like in hyperlinks for writing emails.
The syntax is the same as that of the HTML - Mailto: After "mailto" the address of the recceiver is expected, additionally further parameters can be appended. The first one is split by a question mark ("?") from the receiver address, the others by "&".
The following parameters are possible:
  • cc: Carbon Copy, a copy of the mail is sent to this address, the first receiver sees this.
  • bcc: Blind Carbon Copy, a copy of the mail is sent to this address, the first receiver does not see this.
  • subject: Subject of the message.
  • body: Content of the message.
By the string "%0A" a new line can be inserted in the body.
But attention: Not all email clients support all of these parameters.
The following example opens a window of the standard email program with a message to me:
System.Diagnostics.Process.Start("mailto:bloggeroliver@web.de");

The next command opens a new email window, for which all parameters described above are used:
System.Diagnostics.Process.Start("mailto:bloggeroliver@web.de?bcc=bloggeroliver@web.de&cc=bloggeroliver@web.de&subject=Testmail&body=Hello Oliver,%0Athis mail was created by your sample application.");

Thursday, August 26, 2010

Open Link With Standard Browser

To open a link to an arbitrary website in the standardbrowser using C#, just a call of the function System.Diagnostics.Process.Start() with the target URL as parameter is needed. Then automatically the standard browser opens with the desired webpage.
The following example opens this blog:

System.Diagnostics.Process.Start("http://csharp-tricks-en.blogspot.com/");

Wednesday, August 25, 2010

Registry Tutorial

Today I want to show you how to manage the registry in C#. In this Windows saves information about programms etc., normally it can be accessed via the registry editor (Start - Execute - regedit).
In C# the management is done by the class RegistryKey, which is contained in Microsoft.Win32. For all following code samples I therefor assume

using Microsoft.Win32;
The registry is divided in different categories, on the first level of hierarchy there are for example the groups HKEY_CURRENT_USER (saves settings of the current user) or HKEY_LOCAL_MACHINE (saves settings of the whole computer).
To be able to "use" the registry, first an instance of the class RegistryKey has to be initialized with one of these, for example with:

RegistryKey SampleKey = Registry.CurrentUser;

One can maneuver deeper into the tree with the function OpenSubKey():

RegistryKey DeeperKey = SampleKey.OpenSubKey("Software\\7-Zip"true);

The 2nd parameter of the type Boolean describes, whether the is to be opened with writing rights or not.
DeeperKey then saves the selected key.
For the elementary use there are now only 5 more methods, which I will show directly in an example:
DeeperKey.CreateSubKey("Testkey");
Creates a subkey, if this already exists it is opened
Object TestValue = DeeperKey.GetValue("Lang");
Reads the value "Lang" of the key DeeperKey.
DeeperKey.SetValue("NewValue""randomdata");
Writes "randomdata" in the value "NewValue". If it does not exist yet, it gets created
DeeperKey.DeleteValue("NewValue");
Deletes the value "NewValue".
DeeperKey.DeleteSubKey("Testkey");
Deletes the subkey "Testkey".

Finally, the used objects should be disposed when not used anymore, as the same holds for files etc.
This can be done by the function Close() of the class RegistryKey.

Sunday, August 22, 2010

Start Screensaver

Today I want to show you, how to start the current screensaver of the computer using C#.
Therefor we need a WinAPI function, as always to be able to include this we first need:

using System.Runtime.InteropServices;

The function needed to load the screensaver is SendMessage(), it is included as follows:

[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);

In general this function allows us to send a message to a specific window. The target window is defined by the parameter hWnd.
The 2nd parameter Msg describes the message, which is supposed to be send.
The last 2 parameters allow us to set additional parameters next the message.
To enable the current screensaver, the following parameters are needed:

SendMessage(this.Handle, 0x112, 0xF140, 0);

Thursday, August 19, 2010

Change Mouse Cursor

With C# easily the appearance of the mouse cursor can be changed, so for example instead of the standard arrow head a sand glass can be displayed.
The property which has to be changed for that is calld Cursor, a great collection of mouse cursor symbols can be found in the class Cursors.
Note though, that if you change the cursor with this function, this only holds for the area of the form.
To change the cursor to a hour glass for example (or in Vista or higher to this circling circle), the following code is necessary:

Cursor = Cursors.WaitCursor;

I want to show some more useful symbols:

Cursor = Cursors.AppStarting;



Cursor = Cursors.Arrow;



(Standard symbol) Cursor = Cursors.Default;

Cursor = Cursors.Hand;


Cursor = Cursors.Help;


Cursor = Cursors.No;



Cursor = Cursors.SizeAll;



Cursors.WaitCursor

Wednesday, August 18, 2010

Lock the Computer

In a previous post I explained, how to shutdown the computer using C# or to log out a user. Today I want to show you, how to lock the computer with C# (which can be achieved with Ctrl + Alt + Del - Lock Computer or Win + L).
This action can be done with an API function. As always, to include such a we need the following using directive:

using System.Runtime.InteropServices;

With the following code the needed function then is included:

[DllImport("user32.dll")]
public static extern bool LockWorkStation();

LockWorkStation() now can be called anytime, locking the computer.

Monday, August 16, 2010

InputBox in C#

Many programmers who come from Visual Basic maybe miss the good old InputBox. For those and others who seek a an easy possibility to let the user input data, I today show, how to use the InputBox of Visual Basic.
This calls a modal window, an input box, in which the user can can input data. First a reference to the Visual Basic library is required, which can be added via Project - Add Reference - (Tab .Net) - Microsoft.VisualBasic.
Now the input box can be used via Microsoft.VisualBasic.Interaction.InputBox() in the project.
There are 5 parameters of which only the first one is necessary.
They are:

  1. Text of the input box
  2. Title 
  3. Default input
  4. x coordinate
  5. y coordinate


The function returns the input as a string:

string Response = Microsoft.VisualBasic.Interaction.InputBox("Beispieldialogtext""Titel""Vorgabeantwort", 0, 0);

Above code creates the following InputBox:

Saturday, August 14, 2010

Use Ping in C#

Many probably know the ping command from the command prompt. With this data packages can be send to different addresses, to computers in a network or servers in the internet, for testing purposes.
If they packages are successfully sent and is the destination address reachable, an appropriate response is given.
With the programming language C# such a request can also easily be send. First we have to include the class needed therefor via using:
using System.Net.NetworkInformation;

With the function Send() of the class Ping a ping can be send. The overloading with 1 parameter used here just sets the target address (127.0.0.1 identifies the own computer).
Optinally there can be used more parameters, the 2nd parameter for example sets the time interval, which will be waited for a response.

Ping Sender = new Ping();
PingReply Result = Sender.Send("127.0.0.1");
if (Result.Status == IPStatus.Success)
    MessageBox.Show("Success);
else
    MessageBox.Show("Failure");

Wednesday, August 11, 2010

Determine Word Size of the System

Probably many people do not exactly understand the title, simply said this post is about to determine, whether your computer runs on 32 bit or 64 bit.
This size though is called the word size of the system and therefore is the basic unit of data processing.
On a n bit architecture the system divides all data in words of n bit and operates on these words as a whole. So the greater the word size, the more information can be processes in one calculation step.
But enough theory, in C# one line of code is enough to get this size:

bool Is64Bit = System.Environment.Is64BitOperatingSystem;

Monday, August 9, 2010

Determine Number of Processors

If you want to ask in C# the number of CPU cores in the computer, one command from the class Environment suffices, the property ProcessorCount returns this value:

int NrOfProcessors = Environment.ProcessorCount; 

Saturday, August 7, 2010

Display Overlay Icons in the Taskbar

Following the trend of the previous posts, we stay with nice functions of the Windows API Code Pack. A further new function is the possibility of showing so called Overlay Icons in the taskbar. They are blended over the actual program icon and thus can also display status information, as for example the red cross in the example:





As mentioned, to be able to do so, the Code Pack needs to be included, as is for example described here.
Then the following code induces the showing of an overlay icon:

TaskbarManager tm = TaskbarManager.Instance;
Icon OverlayIcon = new Icon("error.ico");
tm.SetOverlayIcon(OverlayIcon, "Fehler");
The function SetOverlayIcon() determines the icon to be shown, as a first parameter we can use an arbitrary icon, as second a text, which will be displayed alternatively, if the icon is not available.
The following code hides the overlay icon again:

tm.SetOverlayIcon(nullnull);

Thursday, August 5, 2010

Change Style of the Program Icon in the Taskbar

The previous post was about displaying a progressbar in the taskbar, in this post I want to show the use of a similiar function, which is also new in Windows 7.
From Windows 7 on not only a progressbar can be shown, but the program icons can also provide information about the state of the prorgram. Most useful I think are the 2 stati "Error" and "No Response", the following code shows the use of those (like in the previous post described, the Windows API Code Pack is required):

TaskbarManager tm = TaskbarManager.Instance;
tm.SetProgressState(TaskbarProgressBarState.Error);

If above code is run, the program signals an error, the icon is painted slightly red.





As well the program state can be declared as "frozen", then a green bar moves over the icon, which probably a lot of you know:

TaskbarManager tm = TaskbarManager.Instance;
tm.SetProgressState(TaskbarProgressBarState.Indeterminate);

Show Progressbar in Taskbar

From Windows 7 on upwards many new nice features come by, one of them being dynamic icons in the taskbar, which can express the state of the programs.
In this post I want to show you, how to show a progressbar in the program icon in the taskbar, which looks like this:






To create the progressbar, the Windows API Code Pack has to be installed.
If that is the case, we have to add 2 references to the desired project: Therefore select add reference and click Browse, then browse to the folder which contains the code pack.
Then further move to WindowsAPICodePack\Shell. Here our needed .dll files can be found, namely those are Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll.
Then we include the taskbar class in our project:


using Microsoft.WindowsAPICodePack.Taskbar;

The following code then produces a progressbar filled half, which is shown in the icon:

TaskbarManager tm = TaskbarManager.Instance;
tm.SetProgressState(TaskbarProgressBarState.Normal);
tm.SetProgressValue(50, 100);

SetProgressState() determines the style of the application icon, we here tell the prorgamm to look "normal", so we can blend the progressbar over it.
Finally SetProgressValue() sets the progress of the bar, the first overgiven parameter is the current value of the progress, the second one the maximal one.

Wednesday, August 4, 2010

Include the Windows API Code Pack

The Windows API Code Pack is a collection of many useful functionalities, which are yet not implemented in the .Net framework. Many of these will be contained in the next version of .Net, but with the codepack, they can already be used.
Especially for Windows 7 there are many important feautures (in the next post I show for example, how to insert a progress bar in the taskbar logo), but the code pack provides also other interesting features like including Direct X.
The project is open source, meaning its sourcecode is freely available and can be changed by anyone, furthermore it has to be compiled by any user itself.
Therefore I want to give you a short installation information:
You can download the code pack for example on this site, please select here the .zip file.
Extract that and open the C# project WindowsAPICodePack.sln in the folder WindowsAPICodePack.
Now you have to compile the project with Debubbing - Create Project (in my case a reference was missing, therefore I cliked on the project Shell, Add Reference and selected System.Xaml in the tab .Net).
Now the corresponding .dlls are created in the bin - directory. These librariers then can be included in your own projects.

Tuesday, August 3, 2010

Read Time Since Startup

The following snippet shows how to determine the time, the computer is already running since starting, in C#.
With System.Environment.TickCount this value in milliseconds can be read-out in milliseconds.
The example converts this then to an object of the type TimeSpan. This class managages time spans, this way the count of milliseconds can be converted easily in hours, minutes and seconds:

int MsSinceStartup = System.Environment.TickCount; // timespan since startup in milliseconds
TimeSpan TimeDifference = new TimeSpan(0,0,0,0, MsSinceStartup);
MessageBox.Show("Zeit seit Hochfahren: " + TimeDifference.Hours + "h " + TimeDifference.Minutes + "min " + TimeDifference.Seconds + "s"); // output