Using the Begin Invoke method to update the values in other thread

Hi,

Many a times when we are working with multi threaded situation, we want to update the value of another thread from the same. Let say you are working on a windows application which creates a new thread to process some work. Now you want to update the status of work in a label in a windows application.

If you try and update the label’s text property from another thread then you will get a runtime exception. As the other thread cannot access this class variable.

To work around this we have to use the BeginInvoke method to queue the message to the proper thread. Here is the code on how to update a label in a multi threaded environment.

    private delegate void SetLabel1Textdel(string someText);

    private void UpdateLabel1Text(string someText)

    {

Continued...

Using PerformanceCounter class to find the CPU Usage of a given Process

Hi,

Yesterday I was sitting idle and trying to write some dummy windows application. Suddenly I saw that my application is using a lot of CPU resource.

But what if I wanted to know the CPU Usage of an application without using the task manager. Well what if you wanted to show the CPU usage of the current Application to the user. Well I searched a bit and got the answer. So I thought I would share the code with all.

Here is the code for showing the CPU Usage by all the currently running application.
foreach (Process process in Process.GetProcesses())

            {

Continued...

Getting the notification in changes in File system with the help of FileSystemWatcher

Hi,

Yesterday I was playing around with some directories and a requirement came in where by I had to keep watch on the changes in the directory structure. My requirement was to update user as soon a there was a change in a file in the given directory.

I first thought of many ways to do it. By the end I found it was pretty easy to be done. We have to use the FileSystemWatcher class in the System.IO to get the job done.

Lets say we want a notification to be there when there is a change the D drive (D:\). If you want to also make the notification for sub directories then we need to set the IncludeSubdirectories to true. Here is a small code on how to use the component.

FileSystemWatcher watchFiles = new FileSystemWatcher(@"d:\\");

watchFiles.IncludeSubdirectories = true;

string dtCur = DateTime.Now.ToLongTimeString();

Continued...

Finding all the files in a folder recursively after letting the user select the folder through the FileBrowserDialog

Hi,

A few days back I was creating a small utility program for myself. The program needed the user to select a file and then I would get all the file name recursively.

With Dot net framework this was pretty easy. To let the user select a particular file, We can use the inbuilt FolderBrowserDialog. The usage of the dialog is pretty easy.

We first have to create the object of the class. We can optionally give the first selected folder path with the help of the SelectedPath property. To show the dialog we use the following code.

DialogResult result = fbd1.ShowDialog();

Continued...

Process class and some small demo code

Hi

I just found some simple code that I have used in my previous application related to process in a windows application.

Many a time we want to run some external application from our windows application. To do that we need top start the process for that application. Lets say we want to start the WordPad application from our window application.

Process proc = new Process();

proc.StartInfo.FileName = @"Wordpad.exe";

proc.StartInfo.Arguments = "";

proc.Start();

This will start the word pad application in the system. If we give provide an web address as the file name then the default browser will open with the given URL.

Continued...

How to capture the image of the screen according to the resolution using Dot Net

Hi

Today I was playing around with some window form and came up with a simple and interesting requirement. I wanted to take a print screen of the monitor from inside the application. What I wanted to do was allow the user to save the screen as and when they wanted it from inside the application.

So first thing I had to do for this was to find out the resolution of the screen that the user was working with. Because the screenshot need to be save of the same size as the screen resolution. This can be done by using the System.Windows.Forms.SystemInformation class. This class provides a static method PrimaryMonitorSize which gives us the monitor size. This property is of type Size. So we have width and height of the screen using the following code.

int width, height;

width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;

Continued...

Using registry to save configuration setting

Hi

In windows application most of the time we have many configuration data, that need to be maintained for the application. This data can be easily saved in the application setting. But many a time we want to save the data in the registry. Here is how we do that/

To save the configuration values to the registry use the UserAppDataRegistry.SetValue method.

Application.UserAppDataRegistry.SetValue("Value", Value);

Now to load the values from the registry we have to use the getValue method. Always use this method inside the try and catch block because it will throw an exception if the value is not present in the registry.

Also remember to remove all the asterisks in the assembly version from the assembly.cs file and give it a proper assembly version otherwise the registry key will change every time you build the application.

Hope this helps
Thanks
Vikram


How to not allow user to resize the form

Hi

Many a time in a windows application we don’t want user to move or resize the form. For this reason we have three simple options in the windows form.

First of all we can have Border less forms. To make the form borderless we need to set the FormBorderStyle to none. A borderless form cannot be moved. This option has one drawback that the resulting for will not have any border.

Another method would be to set the ControlBox, MinimizeBox, and MaximizeBox properties to False. We lese have to make the text property of the form to and empty string. This time the form will have a raised border but will not be movable.

And the third and easier way to do this is to make the Size, MaximumSize and MinimumSize property of the form to be same. Now the form can’t be resized because the forms current size is both forms maximum size and minimum size.

Continued...

How to save application level settings in windows application
Hi

Many a times in the windows application when you create some settings, we ned to save the settings so that it can be retrieved and used when the user starts the application again. In Dot net this can be done very easily.

You need to save these settings in the Application settings. The scope of these setting should be user and not application. Remember the Settings with the scope of Application are readonly and hence these cannot be changed in the code.

Now to retrieve the settings use the following code

Properties.Settings.Default["SettingName"].ToString();

To change the settings for the user you need to

Properties.Settings.Default ["SettingName"] = "Value";
Properties.Settings.Default.Save();

The setting is changed by setting the property value. But if you do not save the setting the changed setting will not be available next the application restart.

This means that if we only change the setting value then we will get the changed setting
Continued...

Working with different types of socket in Dot net 2.0
Hi
When you are working with the socket class, you can use many socket type. We need to define the type of socket when we create an instance of the socket class. In dot net we have 6 types of Sockets. 
Many a times SocketType implicitly indicates which type of protocolType will be used in the address family. Like when we use the Dgram SocketType the protocoltype will always be Udp. And for Stream SocketType the protocol type will always be Tcp. 
Here is a list of socket types and their uses.
Dgram – This sockettype supports datagrams, which are connection less,
                
Continued...

Some useful code for windows application

Hi

In this post I am going to talk about some of the small but useful code used (or required) very commonly in the Windows application. 

To get the path to all the Important folders on the client machine, we need to use the System.Envirement namespace. We use the GetFolderPath and pass the value of type Environment.SpecialFolder. This way we can get the path to most of the important folders on the clients machine.

Continued...

Using the Web Browser control to show pop-up like window in Windows application

Hi

Yesterday, a client was asking me to open a pop-up for a link. The problem was that the pop-up window is supposed to be open from a windows application. I knew we can open the browser using the code. The code to that is pretty simple.

System.Diagnostics.Process.Start(URL)

Here is the URL is the URL that should be opened in the browser.  If the URL is empty you will get an exception. 

But what the client wanted was to get a pop-up type display without and buttons, address bar etc…

So I decided to use the in built Web Browser control. The control is pretty simple to use and was more than handy for the purpose. Remember this control is new in the dot net 2.0.

Continued...

Different Features of the click once and windows Installer deployment

Hi 

I dot net 2.0 we have to type of Installation available to us. One is click once Installation and another old Windows Installer method. Both the methods have some advantages and disadvantages. Both the technologies are designed with different set of goals and are not a replacement for each other.

There are many compelling features in Click once deployments which are not present in the windows Installer. These features are specifically targeted at developers building .NET Framework-based smart client applications that don't have sophisticated configuration requirements. On the other hand Windows Installer is a much broader deployment technology that is inherently designed to be extensible and able to handle any deployment challenge, including .NET applications. 

Here is a quick look at the features and the availability in both deployment processes.

Continued...

Deploying a windows application in Dot net

Hi

When we create a windows application, deployment is one of the most important issues with it. In dot net deploying a windows application is a very easy task. We can use the one click deployment while the application is in the development phase. But when we need to send the application to the user, the one click deployment is not useful.

We can use the visual Studio’s set-up project to easily create a professional deployment package. I this article I will show how can we create a simple deployment package.

For this purpose we first create a project. The project has only one windows form, which has a button. When you click the button the Application show the current time.

Continued...

Easily Create a Single Instance Windows Application

Hi

Many a time we do not want the user to create the second instance of the (Windows) Application on the same machine. For this we need to restrict the user from opening more than one instance of the application.

The notion of Global and mutex has been introduced by Microsoft to solve this problem. Things like Citrix might fail in condition were you have multi user session (terminal service)

We use the following code to restrict the use of two instance of an application.

  Mutex instanceLock = new Mutex(false, "Name of the Assembly");

Continued...

Passing objects of a class trough the socket

Hi

When we are passing data with the help of Sockets we have to pass the data in byte format. But when we want to use the data we normally use the class structure. So how to work with classes and sockets. Lets say we want to pass a class structure through sockets.

For our example we will take a simple class MessageClass

Our class has three fields and three properties for those fields namely messageType, message, counter

Continued...

Adding and using a resource in dot net

Hi

Many a time we need to add some resources to the windows application, which will be used, by the application during its execution. Like many a time we want to give some sound (.wmv files) with the application, which will be played at certain points in the execution of the Application.

Continued...

Using the new Splitter control in Dot Net 2.0

Hi

A new addition in the Dot net 2.0 Windows control is the splitter control. The splitter control is a combination of many controls with their dock settings. This control can save many steps in the development of a composite control. One of the more common tasks while designing a form is to use controls, which can share the vertical and horizontal space.

Earlier splitter control allowed the application to adjust the division of space separating sections of a container control like panel control. Now we can use the splitter control to eliminate these multiple combined steps.

Continued...

A look at the anonymous methods in C#
Hi

You must be aware of delegates if you have worked in C# before. Even then let me describe delegates my way. Delegates are objects that encapsulate the reference to functions. Implementation of Event Handler code is one of the best examples of delegates.

When we double click on a button on the form to add the handler for that button’s click event, the windows form generate two separate codes. The actual event Handler and a hidden code (found in the designer code) to wire-up the button clicks event.

The code outputted is like this.

private void button1_Click(
  object sender, System.EventArgs e)
{ }

and

Continued...

BackgroundWorker Component for Multi Threaded programming in Dote Net 2.0

Hi

The word Multi threaded programming was a deadly thought earlier. It meant some trouble to me for sure. But now in dot net 2.0 multi threaded programming has been made very vary easy.

The new background worker component makes thing very easy. We can use this component for time-consuming processes and the process that can cause the user interface to act very slowly. The background worker runs those on dedicated separate threads. Some of the good example of uses of background worker would be Database transaction, reading large XML file (or any large file), working with web services, working with sockets, file download and upload etc.

Continued...

New Auto complete property in windows textbox and DropdownList in dot net 2.0
Hi

A new feature added to the Textbox and the DropdownList control in Dot net 2.0 is Auto complete. This allows the user to select the value from previously entered values. User’s recent history is used to display the values.

To enable the AutoComplete property we can use one the three values.

  • Suggest - Appends the rest of the suggested string to the existing entry. The suggested string appears highlighted.
  • Suggest - Displays a drop-down list populated with one or more suggested completion strings.
  • SuggestAppend - Implements both the Suggest and Append options.

The type of Auto complete values displayed can be controlled by AutoCompleteSource property

Hope this helps
Thanks
Vikram


Using the System.Media.SoundPlayer class to play sound
Hi

System.Media Namespace provides many classes to work with the Sound in the application. One of the important classes to play sound is SoundPlayer class. With the help of this class we can simply WAV Files.

The wave files can be loaded by using either the file path, The URL or a stream that contains the .wav file. We can also use an embedded resource that has the .Wav file.

Continued...

How to set the rich textbox to the last line when the text is changed

Recently I was working with Windows form and wanted the scroll of the rich textbox to be on the last line when there was some text changed. I am very new to windows form (having worked mainly in web forms [Asp.Net]).

Then I saw this property of the textbox called ScrollToCaret. So what I did was made the selection start at the end of the textbox and scroll the caret there.

this.txtMessages.SelectionLength = 0;
this.txtMessages.SelectionStart = this.txtMessages.Text.Length;
this.txtMessages.ScrollToCaret();

Continued...
 
Copyright © 2006 - 2008 Vikram Lakhotia