How to Capture System Events using C#

Operating System

What are system events? Well, basically they are events raised by the operating system when a user performs an action which affects the operating environment.

System events are accessible through the Microsoft.Win32.SystemEvents class.

SystemEvents Events

Below is a list of all the system events found within the SystemEvents class.

Name Description
DisplaySettingsChanged Occurs when the user changes the display settings.
DisplaySettingsChanging Occurs when the display settings are changing.
EventsThreadShutdown Occurs before the thread that listens for system events is terminated.
InstalledFontsChanged Occurs when the user adds fonts to or removes fonts from the system.
LowMemory Obsolete. Occurs when the system is running out of available RAM.
PaletteChanged Occurs when the user switches to an application that uses a different palette.
PowerModeChanged Occurs when the user suspends or resumes the system.
SessionEnded Occurs when the user is logging off or shutting down the system.
SessionEnding Occurs when the user is trying to log off or shut down the system.
SessionSwitch Occurs when the currently logged-in user has changed.
TimeChanged Occurs when the user changes the time on the system clock.
TimerElapsed Occurs when a windows timer interval has expired.
UserPreferenceChanged Occurs when a user preference has changed.
UserPreferenceChanging Occurs when a user preference is changing.

[continue reading…]

5 comments

Enumerating and Controlling Windows Services with C#

Operating System

The Microsoft.NET Framework contains a component called the ServiceController. It is designed to allow you to control a Windows Service. With this component you can easily start, stop, and pause services, and you can also retrieve information on the service such as its display name and status among others.

In this article I am going to show you how to use this ServiceController component and also how to enumerate the services running on your pc.

Enumerating Windows Services

To get a list of services running on a pc, we need to use the System.ServiceProcess.ServiceController class. The below code is using a static method called GetServices to return an array of ServiceController objects. Then the array is iterated and we are displaying the services’ information in a ListView component.

private void GetServices()
{
    try
    {
        lstServices.Items.Clear();

        ServiceController[] svcs = ServiceController.GetServices();

        foreach (ServiceController svc in svcs)
        {
            ListViewItem item = new ListViewItem();
            item.Text = svc.DisplayName;
            item.SubItems.Add(svc.ServiceName);
            item.SubItems.Add(svc.Status.ToString());

            lstServices.Items.Add(item);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The below screenshot shows our ListView populated with the Windows services.

[continue reading…]

1 comment

How to use Temporary Files in C#

Files and Directories, Operating System

What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing ‘work data‘. For example Microsoft Office uses temp files to store backups of documents being created or edited. Other applications might use temp files to store large amounts of data which would otherwise occupy too much memory. Basically, it is up to the developer to decide what should be kept within his/her application’s temp files.

In Microsoft Windows, temp files end with the .tmp extension and by default are stored in C:\Users\[username]\AppData\Local\Temp.

The .NET Framework makes creating and using temp files a breeze, so let me show you how to use them.

Create a new Console Application and add a method called CreateTmpFile. In this method we will use the System.IO.Path class to create our temp file.

private static string CreateTmpFile()
{
    string fileName = string.Empty;

    try
    {
        // Get the full name of the newly created Temporary file. 
        // Note that the GetTempFileName() method actually creates
        // a 0-byte file and returns the name of the created file.
        fileName = Path.GetTempFileName();

        // Craete a FileInfo object to set the file's attributes
        FileInfo fileInfo = new FileInfo(fileName);

        // Set the Attribute property of this file to Temporary. 
        // Although this is not completely necessary, the .NET Framework is able 
        // to optimize the use of Temporary files by keeping them cached in memory.
        fileInfo.Attributes = FileAttributes.Temporary;

        Console.WriteLine("TEMP file created at: " + fileName);
    }
    catch (Exception ex)
    {
       Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
    }

    return fileName;
}

[continue reading…]

13 comments

Monitoring the File System for Changes

Files and Directories, Windows Forms

In this article I am going to show you how to monitor a folder for changes. A reason why you might want to do this is for example if you want to keep two files in different locations in sync. When the original file is changed it would trigger an event and you can update the copy in the other location with the updated original file.

The .NET framework provides a component called the FileSystemWatcher which is designed to do exactly what its name suggests – watch the file system for changes. Let’s create an example which uses this component.

Create a new Windows Forms Application project and design a form which looks similar to the one below:

Then add a FileSystemWatcher component to your form from the Components Toolbox in Visual Studio.

Next we’ll configure the FileSystemWatcher and start monitoring a folder in the Monitor button’s event handler. The code for this is shown below:

private void btnMonitor_Click(object sender, EventArgs e)
{
    try
    {
        // Watch for changes on this path
        fileSystemWatcher.Path = txtPath.Text.Trim();
        
        // Watch for changes on all files
        fileSystemWatcher.Filter = "*.*";

        // Also watch for changes within sub directories
        fileSystemWatcher.IncludeSubdirectories = true;

        // Begin watching
        fileSystemWatcher.EnableRaisingEvents = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

[continue reading…]

1 comment

Formatting Decimals in C#

String Operations

In this post I am going to show you a few different ways how you can format a decimal number (float, double, or decimal).

Setting the Maximum Allowed Decimal Places

To format your numbers to a maximum of two decimal places use the format string {0:0.##} as shown in the below example:

string.Format("{0:0.##}", 256.583); // "256.58"
string.Format("{0:0.##}", 256.586); // "256.59"
string.Format("{0:0.##}", 256.58);  // "256.58"
string.Format("{0:0.##}", 256.5);   // "256.5"
string.Format("{0:0.##}", 256.0);   // "256"

Setting a Fixed Amount of Decimal Places

This is similar to the above example but instead of hashes (‘#’) in our format string we are going to use zeroes (‘0’) as shown below:

string.Format("{0:0.00}", 256.583); // "256.58"
string.Format("{0:0.00}", 256.586); // "256.59"
string.Format("{0:0.00}", 256.58);  // "256.58"
string.Format("{0:0.00}", 256.5);   // "256.50"
string.Format("{0:0.00}", 256.0);   // "256.00"

The Thousand Separator

To format your decimal number using the thousand separator, use the format string {0:0,0} as shown in the below example:

string.Format("{0:0,0.00}", 1234256.583); // "1,234,256.58"
string.Format("{0:0,0}", 1234256.583);    // "1,234,257"

[continue reading…]

19 comments