Search:

Custom Search
_________________________________________________________________

Thursday, June 19, 2008

Writing Registry keys

We saw before how to read a registry key. Writing is similar and also accomplished by the RegistryKey object. C# .Net provides very easy methods under this object to write keys.

Be aware that the registry is a key part of an Operating System so you should know exactly what you are doing before actually doing it. Check every single line of the code written. On this example I’ll show you below, I will create a couple of keys with its proper folder too. By doing this I can be sure that any other registry key would be overwritten.

Take a look now at this example:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace WritingRegKeys
{
class Program
{
static void Main(string[] args)
{

RegistryKey RegKeyWrite = Registry.CurrentUser;
RegKeyWrite = RegKeyWrite.CreateSubKey
("Software\\MySoftware\\SubKeys");
RegKeyWrite.SetValue("Try", "True");
RegKeyWrite.SetValue("NumberValue", 1);

RegKeyWrite.Close();

RegistryKey RegKeyRead = Registry.CurrentUser;
RegKeyRead = RegKeyRead.OpenSubKey("Software\\MySoftware\\SubKeys");
Object regTry = RegKeyRead.GetValue("Try");
Object regNumber = RegKeyRead.GetValue("NumberValue");
RegKeyRead.Close();
Console.WriteLine("Try value: " + (String)regTry + " - - NumberValue: " + regNumber);

}
}
}

You can see that after creating the RegistryKey object I also created a subkey with the CreateSubKey method. This will generate another “subfolder” under MySoftware.

The Complete root is: HKEY_CURRENT_USER\Software\MySoftware\SubKeys.

With the RegKeyWrite.SetValue you have to specify the name of that key and the actual values you want to be stored. You can see that the fist value to be stored is a String and the second a Numeric value.

You can try this by reading the keys created above. That why the RegKeyRead Object is also created. Then we just open the SubKey and ask the values for the Try key and the NumberValue key. Run the code and the Console should look something like this:

When you execute the code, a new registry should be created. So let’s take a look at the registry to see if this is true. Open regedit to see the changes.


Saturday, June 7, 2008

Accessing the Registry for reading keys in C#

C# contains class object that make the job of manipulating the registry very easy.
Also, the registry is indexed that make much faster the reading job.

Ok, let’s now proceed to read from the registry.
First you need to make the import of the Microsoft.Win32 namespace that contains the registry access functions.
The second important thing you need to use RegistryKey object to make the actual reading.

Let’s now write a small piece of code to see how this works.

using System;
using System.Text;
using Microsoft.Win32;

namespace RegRead
{

class Program
{

static void Main(string[] args)
{


//Example 1
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(
"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\1");
Object cpuName = RegKey.GetValue("ProcessorNameString");
Console.WriteLine("Your CPU name is:" + cpuName);

Console.WriteLine("");

//Example 2
RegistryKey RegKey2 = Registry.CurrentUser;
RegKey2 = RegKey2.OpenSubKey("Printers");
Object printerName = RegKey2.GetValue("DeviceOld");
Console.WriteLine("Your Printer name is: " + printerName);

Console.Read();
}
}
}


The first thing you need to do is to import the Microsoft.Win32 namespace.
Then, if you look at the definition of the instance of the RegistryKey object, you will see that it is pointing to Local Machine, which means that the HKEY_LOCAL_MACHINE folder will be enable for reading.

(To open the Registry editor just go to start->Run: regedit).
After this step, we simple need to find the folders/subfolders where the key is located and read it.

The second example is pretty much the same. The only major difference is that the
HKEY_CURRENT_USER folder will be available.

Friday, May 30, 2008

Advance C# programming, overload unary plus.

C# let’s you overload the behaviour of some unary operator such as: unary plus, minus, prefix increment, decrement, true keyword, false keyword and more.

Ok, now let’s make a small example on how to overload the unary plus. For this, you need to define a method (in the class that you want to implement the overload) containing a few things: the return type, the operator keywords (in this case +), the parameter that usually is the object or structure where the method is being defined.

Let’s make now a small example:

-First we create a small class and define the overload plus:

public class MyClass
{

public double value;

public static MyClass operator +(MyClass Mc)

{
MyClass myC = new MyClass();
if (Mc.value <0)
myC.value = -Mc.value;

else
myC.value = Mc.value;

return myC;
}

}

-Main:

static void Main(string[] args)
{

MyClass MyCs = new MyClass();
MyClass MyCsP = new MyClass();

//Both negative and positive values to see effect
MyCs.value = -10.80;
MyCsP.value = 300;

Console.WriteLine("Before: " + MyCs.value);
Console.WriteLine("\t" + MyCsP.value);

//Using the + operator triggers the method
MyCs = +MyCs;
MyCsP = +MyCsP;

Console.WriteLine("After: " + MyCs.value);
Console.WriteLine("\t" + MyCsP.value);

Console.Read();

}

-Console:

Monday, May 19, 2008

MouseDown Event in C#.

The MouseDown event is the one I personally use every time a control needs both events for left and right click (middle click is also supported).
So lest say we want to add the mouseDown event to a Button control somewhere in a windows form. So you can go ahead and add this event.

This header shows appear in the form:

private void button2_MouseDown(object sender, MouseEventArgs e)

So lets proceed to add some code here.
The way to see which button has been clicked is by using a switch statement:

switch (e.Button)
{

case MouseButtons.Left:

//Place here event for left click

break;

case MouseButtons.Right:

//Place here event for right click

break;

default:

break;

}

Great, now your application can distinguish between lest and right click.
To make sure this works, you can add a messageBox saying what event should run.

Complete Code:

private void button2_MouseDown(object sender, MouseEventArgs e)
{

switch (e.Button)
{

case MouseButtons.Left:

MessageBox.Show(this, "Left Button Click");

break;

case MouseButtons.Right:

MessageBox.Show(this, "Right Button Click");

break;

default:

break;

}
}

Wednesday, May 7, 2008

Creating Tooltip to Button Control from scratch

First of all, start by creating a new Windows form application in Visual Studio 2005. (You can download the Express Edition clicking the link on My Links section).

After that, place a Button Control somewhere in the form as you see below:

Ok, now we can proceed to add the tooltip event to the button1. This is actually very easy. I will show you the way I use for doing this.

Navigate through the toolbox until you find the tooltip control. Grab the control and place it somewhere in the form.

You will see that the Control is placed in a bar below the form. Also the Tooltip Control is created with the name tooltip1. Ok, now let’s add some event and write a few code lines.

Click the button1 and under properties double click the MouseHover event. This creates the method that we use for the tooltip control. Now in the method body add this line of code:

toolTip1.SetToolTip(button1, "Information for Button1");

Great, now run the app and see what happens. It should look something like this:


Some other cool features on this C# Control:
-
toolTip1.IsBalloon = true;
(Converts to a ballon window)



- toolTip1.ToolTipIcon = ToolTipIcon.Error;
(Assign icon to the tooltip)

- toolTip1.ToolTipTitle = "This is the Title";
(Assigns a title)

Complete Code:

private void button1_MouseHover(object sender, EventArgs e)
{
toolTip1.SetToolTip(button1, "Information for Button1");
toolTip1.IsBalloon = true;
toolTip1.ToolTipIcon = ToolTipIcon.Error;
toolTip1.ToolTipTitle = "This is the Title";
}

Monday, April 28, 2008

Deleting elements from a list while iterating

In C# you are not allowed to iterate and delete elements from a list at the same time. So what you need to do is to find a way to delete these elements later, after knowing what you are going to eliminate. In C++ you won’t have this problem but in C# an exception will be triggered.

This example below demonstrates how to solve this nicely. Basically what it does is that looks for none existing files from your hard drive and saves these on a separate List. Suppose that the object Element contains a string value representing a file path:

public void validateList() {

//New list that will contain the Objects to be deleted later on.
List<Element> listToDelete = new List<Element>();

//ListAll contains all the Element objects
foreach (Element e in listAll()) {
string location = e.loc;
if(!File.Exists(location)){
listToDelete.Add(e);
}

}
foreach (Element e in listToDelete) {
listAll.Remove
(e);
}

}

Sunday, April 20, 2008

Text file Reading and Writing in C#

This program below demonstrates the use of StreamWriter and StreamReader (both derive form the abstract type TextWriter and TextReader respectively). The .Net Framework has simple solutions to work with files. When working with text files there are usually three common steps:

1- Opening the file
2- Reading/Writing
3- Closing it

Now, lets take a look at this example:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication
{

class Program
{

public static void Main(string[] args)
{

//C# Code for writing into a file we call: File.txt

FileInfo f = new FileInfo("File.txt");
StreamWriter Text = f.CreateText();

//Insert text in separate lines
Text.WriteLine("-->Line One content");
Text.WriteLine("--->Line Two Content");

//Insert text but does not create a new line
Text.Write("---->Line Three ");
Text.WriteLine("Content");

//To create new Line.
Text.Write(Text.NewLine);
Text.WriteLine(System.DateTime.Now);
Text.Close();

//Calling the method to read File.txt
readFiles();

Console.Read();


}
public static void readFiles()
{

//We open File.txt
StreamReader sr = new StreamReader("File.txt");
string lines = null;

//Here we do a while loop in order to look for none empty lines.
while ((lines = sr.ReadLine()) != null)
{
Console.WriteLine(lines);
}

sr.Close();
}

}
}

Thursday, April 10, 2008

Connection to a data source in C#

Here is an easy way to get access for example, to an Access database located in your program folder using ADO .NET .

//Add this namespace for database handle
using System.Data.OleDb;

public OleDbConnection GetConnection()
{

OleDbConnection acc = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb";

return acc;

}

Later, when you want to open the database to load, save or whatever you need to do you can use the sentence, being Instance() a method used by Singleton pattern and ConnectionMgr the class name for managing connections:

IDbConnection acc = ConnectionMgr.Instance().GetConnection();