Issue dated - 3rs February 2003

-


CURRENT ISSUE
INDIA NEWS
INDIA TRENDS
STOCK FILE
OPINION
NEWS ANALYSIS
E-BUSINESS
COMPANY WATCH
TECHSPACE
IND. COMPUTES
PERSONAL TECH.
BOOK REVIEWS
PRODUCTS
EVENTS
COLUMNS
TECH FORUM

THE C# COLUMN

BETWEEN THE BYTES
TECHNOLOGY
SPECIALS <NEW>
HMA BANKBIZ
EC SERVICES
ARCHIVES/SEARCH
IT APPOINTMENTS
WRITE TO US
SUBSCRIBE/RENEW
CUSTOMER SERVICE
ADVERTISE
ABOUT US

 Network Sites
  IT People
  Network Magazine
  Business Traveller
  Exp. Hotelier & Caterer
  Exp. Travel & Tourism
  Exp. Backwaters
  Exp. Pharma Pulse
  Exp. Healthcare Mgmt.
  Express Textile
 Group Sites
  ExpressIndia
  Indian Express
  Financial Express

 
Front Page > TechSpace > Story Print this Page|  Email this page

Accessing the Windows registry

The C# Column

The Windows registry is used to store all the configuration information relating to Windows setup, user preferences, software installed and the devices. The registry is arranged in a hierarchical tree-like structure and can be viewed using the popular regedit utility. Each node (folder in a yellow colour) in this tree is called a key.

Each key can contain additional keys or sub-keys (which allow further branching) as well as values that are used to store the actual data. Each registry key may have several values and each value comprises of name-data pair.

For example, a registry key ‘Desktop’ may have values like ‘Wallpaper’, ‘TileWallpaper’, etc. Each value in a key contains the actual data. This data may take several forms ranging from a simple integer value to a user-defined binary object. Each type is represented by a special registry specific type. For example, an integer is represented by REG_DWORD and a string is represented by REG_SZ.

Many applications store their status (information like ‘last file opened in the application’, ‘options selected by the user’, and so on) in registry. We shall also create such an application that stores the background image, foreground colour, size of the window and its position in the registry so that the next time the application is run these selections can be used to build the window.

For accessing the registry we will use the Registry and RegistryKey classes available in the Microsoft.Win32 namespace. Naturally, we will have to add a using statement for this namespace.

Create a Windows Application and design a form as shown in the following screen shot:

Also add the OpenFileDialog and ColorDialog controls to the form. Name them as file and color respectively. The ‘Choose Bitmap’ button allows the user to select an image file through the ‘Open’ file dialog. The ‘Choose Color’ button lets the user select a foreground colour through the standard ‘Color’ dialog.

To store the information of our application we will create a tree structure of two sub-keys-Theme and Settings under the ‘HKEY_LOCAL_MACHINE/SOFTWARE’ key. The Settings sub-key would contain all the values and data. Each key we want to access is represented by an object of the RegistryKey object. So, create the objects that would represent the SOFTWARE key and two user-defined keys as shown below:

	RegistryKey skey, tkey, rootkey;

To write anything in registry keys, we must open them. If keys are not created, we must first create them. We would do this in constructor after a call to the InitializeComponent( ) method. Add the following statements to the constructor:

	rootkey=Registry.LocalMachine.OpenSubKey(“SOFTWARE”, true);
	tkey=rootkey.CreateSubKey(“Theme”);
	skey = tkey.CreateSubKey(“Settings”);

In a file system, root drives like C:\ or D:\ are the root directories. In the registry, there are root keys called ‘registry hives’ or ‘base keys’. There are seven such registry hives. The Registry class provides seven fields of type RegistryKey representing the seven registry hives. The LocalMachine field represents the HKEY_LOCAL_MACHINE base key. The OpenSubKey( ) method opens the key. Since we have called the method using LocalMachine field, it would open the SOFTWARE key of Local Machine hive. By passing true as the second parameter we have specified that the key is to be opened for writing. Next, we have created the ‘Theme’ sub-key in the SOFTWARE key and ‘Settings’ in the ‘Theme’ sub-key. We have called the CreateSubKey( ) method for this.

Now let us add handlers for the buttons. The b_bitmap_Click( ) handler gets called when the ‘Choose Bitmap’ button is clicked.

 private    void b_bitmap_Click ( object sender, System.EventArgs e )
   {
   file.Filter = “Image Files (*.bmp,*.gif,*.jpg)|*.bmp;*.gif;*.jpg||”    ; 
   if ( file.ShowDialog( ) == DialogResult.OK )
   {
   BackgroundImage = Image.FromFile ( file.FileName ) ;
   skey.SetValue (“Image”, ( string ) file.FileName ) ;
   }
   }

Here, we have displayed the ‘open’ dialog. We have applied a filter so that only image files get displayed. If the user selects file we have changed the background image of the form and also written the file path as data of the ‘Image’ value in the ‘Settings’ sub-key. We have called the SetValue( ) method for writing the data. The SetValue() method takes the value name and data as parameters. The data needs to be typecast in suitable type as the method takes parameter of type object.

The b_color_Click( ) method gets called when clicked on the ‘Choose Color’ button. The handler is given below.

 private void b_color_Click    (object sender, System.EventArgs e )
   {
   if ( color.ShowDialog( ) == DialogResult.OK ) 
   {
   ForeColor = color.Color ;
   skey.SetValue ( “Red”, ( int ) color.Color.R ) ;
   skey.SetValue ( “Green”, ( int ) color.Color.G ) ;
   skey.SetValue ( “Blue”, ( int ) color.Color.B ) ;
   }
   }

Finally add the code to write size and position to the registry. This code should get executed when the window is closed. So, we would add this code in the Dispose( ) method. The Dispose( ) method is given below:

 protected override    void Dispose ( bool disposing )
   {
   skey.SetValue ( “Height”, ( int ) Height ) ;
   skey.SetValue ( “Width”, ( int ) Width ) ;
   skey.SetValue ( “X”, ( int ) DesktopLocation.X ) ;
   skey.SetValue ( “Y”, ( int ) DesktopLocation.Y ) ;
   skey.Close( ) ;
   tkey.Close( ) ;
   rootkey.Close( ) ;
   // AppWizard generated code
   }

After writing the values we have closed the keys by calling the Close( ) method. Now our writing part is over. We want that when the application is executed the next time, the form should get displayed the same way as it was before closing. To read the information from registry, we have written a user-defined method readsettings().

	public void readsettings()
   {
   	rootkey = Registry.LocalMachine.OpenSubKey ( “SOFTWARE”, false ) ;
 		tkey = rootkey.OpenSubKey ( “Theme” ) ;
		if ( tkey == null )
		return ;
		skey = tkey.OpenSubKey ( “Settings” ) ;
		string f = ( string ) skey.GetValue ( “Image” ) ;
		if ( f != null )
		BackgroundImage = Image.FromFile ( f ) ;
		try
		{
			int r = ( int ) skey.GetValue ( “Red” ) ;
			int g = ( int ) skey.GetValue ( “Green” ) ;
			int b = ( int ) skey.GetValue ( “Blue” ) ;
			ForeColor = Color.FromArgb ( r, g, b ) ;
			Height = ( int ) skey.GetValue ( “Height” ) ;
			Width = ( int ) skey.GetValue ( “Width” ) ;
			int x = ( int ) skey.GetValue ( “X” ) ;
			int y = ( int ) skey.GetValue ( “Y” ) ;
			DesktopLocation = new Point ( x, y ) ;
		}
		catch ( Exception e )
		{
			return ;
		}
	}

Here, firstly we have opened the keys. When the application is run for the first time, keys are not created. So, we have checked for the null reference in the RegistryKey object. The statements written thereafter read the data from registry and use it. Call this method from the InitializeComponent() method after the initialisation code.

Yashavant Kanetkar, one of the first Express Computer columnists, is an established software expert, speaker and author with several best-sellers to his credit, including titles like “Let Us C” and the “Fundas” series. Contact him at kanet@nagpur.dot.net.in
<Back to top>


© Copyright 2000: Indian Express Group (Mumbai, India). All rights reserved throughout the world. This entire site is compiled in
Mumbai by The Business Publications Division of the Indian Express Group of Newspapers.
Please contact our Webmaster for any queries on this site.