Archive for the 'Tip' Category



C# How to: Drawing in GDI with Opacity/Alpha components

Article Purpose

In this article we explore GDI+ drawing operations implementing opacity, also known as alpha blending.

Sample source code

This article is accompanied by a sample source code Visual Studio project which is available for download here

C# How to: Drawing in GDI with Opacity/Alpha components

Using the Sample Application

The following is a screenshot of the included sample application:

GDIOpacityDrawing

The screenshot illustrates drawing text and a rectangle onto a Windows Form in Color.SteelBlue with an alpha component of 100.

GDI+ Drawing

In C# it is possible and relatively easy to draw text and two dimensional shapes in GDI+ that support a level of opacity or transparency. The well known abbreviation RGB abbreviates the term Red, Green and Blue. C# supports RGB colours but also what is known as ARGB colours. In the case of ARGB the A abbreviates the word Alpha, in other words an RGB colour with a specified alpha component.

An alpha component specifies a colour’s opacity or transparency. Possible values range from 0 to 255 inclusive, where 0 would represent full transparency and 255 no level of transparency. If a consists of 8 bits and an ARGB colour is composed of 4 components ranging from 0 to 255 each representing a or 8 bits, then an ARGB colour is therefore a 32 bit colour.

The Color structure

The System.Drawing namespace defines the Color structure, which exposes several functions aimed at creating an ARGB Color object instance:

The Paint Event Handler

The bulk of this example’s functionality occurs within the main Form’s handler, as detailed by the following code snippet:

private void MainFormPaintEventHandler(object sender, PaintEventArgs e) 
{ 
    Color alphaForeColor = Color.FromArgb(this.foreColorAlphaValue, this.ForeColor); 
    Pen rectanglePen = new Pen(alphaForeColor, 2.0f); 
    SolidBrush textBrush = new SolidBrush(alphaForeColor); 

float x = this.ClientRectangle.Width / 2.0f; x -= e.Graphics.MeasureString(textToDisplay, this .Font).Width / 2.0f;
float y = this.ClientRectangle.Height / 2.0f; y -= e.Graphics.MeasureString(textToDisplay, this.Font).Height / 2.0f;
e.Graphics.DrawString(textToDisplay, this.Font, textBrush, new PointF(x, y));
e.Graphics.DrawRectangle(rectanglePen, 25, 25, this.ClientRectangle.Width - 50, this.ClientRectangle.Height - 50); }

The main Form defines two member variables used in the handler:

 private byte foreColorAlphaValue = 100;
 textToDisplay = "http://softwarebydefault.com";

In the handler an instance of the structure is created implementing an alpha component defined by the ’s member variable. The object declaration is followed by an ARGB   Pen and SolidBrush declaration.

Next the code determines the X and Y coordinates that would result in drawing the ’s string member variable in the middle of the , after which the actual drawing occurs.

Using the Pen object declared earlier a rectangle is drawn 25 pixels inside the ’s ClientRectangle.

C# How to: Determine free space on a drive

DriveInfo Class

Being able to determine the amount of space not in use on a particular drive from C# code is very easy and straight forward. Various properties relating to a logical Windows drive can be determined by implementing the System.IO.DriveInfo class.

The DriveInfo class exposes two public properties relating to drive space not in use:

The difference between these two properties is that AvailableFreeSpace takes into account user configured disk quotas in Windows. AvailableFreeSpace therefore represents the total amount of free space available to the currently logged in user. In contrast TotalFreeSpace represents the total amount of space free on the specified drive, regardless of restrictions/quotas on the currently logged in user’s account.

To be safe use AvailableFreeSpace when doing file IO operations such as copying, downloading or creating new files.

I have written an example application that implements two extension methods which allows the calling code to specify the measurement unit (Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes) in which to return TotalFreeSpace or AvailableFreeSpace.

Code Sample

Download the source code here

This code sample implements the DriveInfo Class’ AvailableFreeSpace  and TotalFreeSpace properties and creates two extension methods allowing the calling code to specify the measurement unit (Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes)

DiskSizeUnit enum

Both extension methods expects as a parameter an enum value of type DiskSizeUnit. The value will determine the unit in which AvailableFreeSpace or TotalFreeSpace gets returned.

1: public  enum  DiskSizeUnit
2: {
3:     Bytes = 0,
4:     KiloBytes = 1,
5:     MegaBytes = 2,
6:     GigaBytes = 3,
7:     TeraBytes = 4
8: }
9:

Total Free Space

The TotalFreeSpaceFormatted extension method accepts as its first parameter an object of type DriveInfo, indicating that this method acts as an extension method to the DriveInfo Class. The second parameter is an enum instance of type DiskSizeUnit, which is used to determine the measurement unit in which to return the DriveInfo class’ TotalFreeSpace property.

1: public  static  double  TotalFreeSpaceFormatted(this DriveInfo  driveInfo, DiskSizeUnit  sizeUnit)
2: {
3:     double  freeSpace = -1;
4:     double  formatDivideBy = 1;
5:
6:     if  (driveInfo != null )
7:     {
8:         long  freeSpaceNative = driveInfo.TotalFreeSpace;
9:         formatDivideBy = Math.Pow(1024, (int )sizeUnit);
10:
11:         freeSpace = freeSpaceNative / formatDivideBy;
12:     }
13:
14:     return  freeSpace;
15: }

The method first checks if the DriveInfo object has been instantiated (line 6). In order to convert TotalFreeSpace, which is expressed in bytes, the value is divided based on the value of the DiskSizeUnit enum parameter passed to this method. As an example if DiskSizeUnit.MegaBytes is specified, the Math.Pow() method will return 1048576 (1024 * 1024), as shown on line 9. Dividing a value expressed in bytes by 1024 and again by 1024 will return a value representing the original byte value expressed in megabytes.

Note: DriveInfo.TotalFreeSpace will return the number of bytes not in use on a particular drive. This property does not take into account limitations/restrictions on the currently logged in user such as Disk Quotas defined by Windows User Accounts.

Available Free Space

The AvailableFreeSpaceFormatted extension method accepts as its first parameter an object of type DriveInfo, indicating that this method acts as an extension method to the DriveInfo Class. The second parameter is an enum instance of type DiskSizeUnit, which is used to determine the measurement unit in which to return the DriveInfo class’ AvailableFreeSpace property.

1: public  static  double  AvailableFreeSpaceFormatted(this  DriveInfo  driveInfo, DiskSizeUnit  sizeUnit)
2: {
3:     double  freeSpace = -1;
4:     double  formatDivideBy = 1;
5:
6:     if  (driveInfo != null )
7:     {
8:         long  freeSpaceNative = driveInfo.AvailableFreeSpace;
9:         formatDivideBy = Math .Pow(1024, (int )sizeUnit);
10:
11:         freeSpace = freeSpaceNative / formatDivideBy;
12:     }
13:
14:     return  freeSpace;
15: }

Internally this method works almost exactly the same as the TotalFreeSpaceFormatted extension method. The only difference being checking and formatting through division the DriveInfo.AvailableFreeSpace property.

Note: DriveInfo.AvailableFreeSpace takes into account limitations/restrictions on the currently logged in user’s account such as Disk Quotas defined by Windows User Accounts.

Test Application

As part of this code sample a Console based test application is provided.

DriveSpaceAvailable

The test application determines the drive letter of the current directory using Environment.CurrentDirectory and Path.GetPathRoot.

1: if (Environment .CurrentDirectory != String .Empty)
2: {
3:     string  driveLetter = Path .GetPathRoot(Environment .CurrentDirectory);
4:
5:     DriveInfo  drive = new  DriveInfo (driveLetter);
6:
7:     Console .WriteLine("TotalFreeSpace: {0,0:F3} B" ,
8:     drive.TotalFreeSpace);
9:
10:     Console .WriteLine();
11:     Console .WriteLine("TotalFreeSpaceFormatted:" );
12:
13:     Console .WriteLine("{0,0:F3} B" ,
14:     drive.TotalFreeSpaceFormatted(DiskSizeUnit .Bytes));
15:
16:     Console .WriteLine("{0,0:F3} KB" ,
17:     drive.TotalFreeSpaceFormatted(DiskSizeUnit .KiloBytes));
18:
19:     Console .WriteLine("{0,0:F3} MB" ,
20:     drive.TotalFreeSpaceFormatted(DiskSizeUnit .MegaBytes));
21:
22:     Console .WriteLine("{0,0:F3} GB" ,
23:     drive.TotalFreeSpaceFormatted(DiskSizeUnit .GigaBytes));
24:
25:     Console .WriteLine("{0,0:F3} TB" ,
26:     drive.TotalFreeSpaceFormatted(DiskSizeUnit .TeraBytes));
27:
28:     Console .WriteLine();
29:
30:     Console .WriteLine("TotalFreeSpace: {0,0:F3} B" ,
31:    drive.AvailableFreeSpace);
32:
33:     Console .WriteLine();
34:     Console .WriteLine("AvailableFreeSpaceFormatted:" );
35:
36:     Console .WriteLine("{0,0:F3} B" ,
37:     drive.AvailableFreeSpaceFormatted(DiskSizeUnit .Bytes));
38:
39:     Console .WriteLine("{0,0:F3} KB" ,
40:     drive.AvailableFreeSpaceFormatted(DiskSizeUnit .KiloBytes));
41:
42:     Console .WriteLine("{0,0:F3} MB" ,
43:     drive.AvailableFreeSpaceFormatted(DiskSizeUnit .MegaBytes));
44:
45:     Console .WriteLine("{0,0:F3} GB" ,
46:     drive.AvailableFreeSpaceFormatted(DiskSizeUnit .GigaBytes));
47:
48:     Console .WriteLine("{0,0:F3} TB" ,
49:     drive.AvailableFreeSpaceFormatted(DiskSizeUnit .TeraBytes));
50: }
51:
52: Console .WriteLine();
53: Console .WriteLine("Press any key to exit" );
54: Console .ReadKey();
55:

*I want to give credit and say a big thank you to Vitaly Zayko. All the code snippets Html markup in this article was generated using his Visual Studio Extension Code4Blog.

[tweetmeme source=”DefaultSoftware” only_single=”false”]

Shutdown Windows without installing updates

Yesterday I shutdown my notebook  as I was about to leave work. Surprise! There was a couple of hundred Windows updates waiting to be installed. Yes, I’m talking about the dreaded “Install updates and shutdown”, which can take anywhere from a couple of seconds to hours.

I have no problem with installing Windows updates, I think keeping up to date with security updates and bug fixes are important. The problem I do have is in having to wait, especially after a day at the office, having the expectation of freedom shattered by painfully watching updates installing one by one.

If you don’t have time to wait for updates to install and you simply want to shut down, there is a way out. Close your desktop. When viewing your desktop enter alt+F4, which is the general close program command. In the case of the desktop you will be presented with an options menu. One of the options being “Shut Down”, allowing you to bypass “Install updates and shut down”.

Updates

My First post using Windows Live Writer!

I’ve installed and configured Windows Live Writer. The initial to My WordPress Blog was really effortless and without incident. I created this post using the Live Writer Desktop application, so far so good. Browser based WYSIWYG () have certainly improved vastly, but I still prefer the ease and control of a desktop based word editor.

Open a Website from C#

It is often a requirement to open the default web browser and browse to a specific Url from a Windows Forms, WPF or even Console application. The easiest method I’ve discovered is to make use of the System.Diagnostics.Process class:

 using  System;
 using  System.Collections.Generic;
 using  System.Text;
 using  System.Diagnostics;
 
 namespace  OpenDefaultBrowser
 {
     class  Program 
     {
         static  void  Main(string [] args)
         {
             Process .Start("http://softwarebydefault.com" );
         }
     }
 }
 

In most scenarios the code snippet listed above works without a problem. The only issue I foresee being in an environment where the user account used to execute your application not having sufficient permissions to execute the default browser application.

For more information see MSDN Process Class


Dewald Esterhuizen

Unknown's avatar

Blog Stats

  • 893,577 hits

Enter your email address to follow and receive notifications of new posts by email.

Join 91 other subscribers

Archives

RSS SoftwareByDefault on MSDN

  • An error has occurred; the feed is probably down. Try again later.