Tag Archives: C#

How to draw Listbox items with alternative background colors

Some people find it easier to read large amount of data when the rows have an alternative background color instead of always the same. This is called Zebra Striping.

For this example we will look into implementing this technique for our ListBox control so it will look similar to this:
Listbox zebra striping

First we need to ensure that the ListBox.DrawMode property is set to DrawMode.OwnerDrawFixed. This can be accomplished by either changing the property in the properties window or by placing listBox1.DrawMode = DrawMode.OwnerDrawFixed; in your form’s constructor or any of the load events.

Then we need to handle the ListBox’s DrawItem event so we can change the colors as we like.

And we are done ! Feel free to modify the example to suit your needs.

How to allow only one application instance

The following code will ensure that your application can only have one instance active. If the user tries to open the application again while the application is already running then the application will simply quit (in this case after showing a message).

For this to work we will need to modify the Program.cs to check with the use of Mutex if the application is already running or not before we open the main form. Our check will take place in the Main method.

Your code in Program.cs should look like this:

Feel free to modify the example to suit your needs.

Get value between two strings

You might find this snippet particular useful in cases where you want to get a value between two other values.

This takes advantage of the string’s Split overload to pass an array of two values. This will result in the string being split twice, once for the first value in the array and once more for the second value. The result will be that the second value in the array that Split returns is the actual value between the first and the second value we passed as argument.

Code:

Example:

How to get the short path of a directory

In some occasions it might be necessary to use a directory’s short path. This is possible with the use of the Windows GetShortPathName function.

Implementation:

Simply call the GetShortPath with the directory you want to get the short path as an argument.

Example:

Calculate file checksum

You might have noticed by now that a lot of websites list their files checksum values in their downloads section. Checksums are extremely useful when you want to verify that the file you have downloaded from another source is indeed the same file that is hosted on the official website and that it has not been altered in any way.

For this very reason I’ve put together a method that will generate the checksum of the file of your choice. Simply provide the location of the file and the algorithm you wish to compute the checksum with.

Examples: