@manhng

Welcome to my blog!

WinForm samples

January 27, 2018 10:46

WinForm samples:

  • How to run only a Single Instance of the Application using Windows Forms
  • Top 10 Windows Forms Articles You Must Read
  • 30 Common String Operations in C# and VB.NET
  • Some Common Conversion Functions
  • ComboBox Control Recipes
  • How to Localize Windows Forms and Change the Language at Runtime
  • How to randomly reorder an ArrayList and Refresh the ComboBox contents at Runtime

http://www.dotnetcurry.com/tutorials/winforms

Top 10 Windows Forms Articles You Must Read

http://www.dotnetcurry.com/ShowArticle.aspx?ID=204

30 Common String Operations in C# and VB.NET (Part 1)

http://www.dotnetcurry.com/csharp/189/csharp-string-substring-split-functions

30 Common String Operations in C# and VB.NET (Part 2)

http://www.dotnetcurry.com/ShowArticle.aspx?ID=190

Some Common Conversion Functions

http://www.dotnetcurry.com/ShowArticle.aspx?ID=97

How to Localize Windows Forms and Change the Language at Runtime

http://www.dotnetcurry.com/ShowArticle.aspx?ID=174

How to randomly reorder an ArrayList and Refresh the ComboBox contents at Runtime

http://www.dotnetcurry.com/ShowArticle.aspx?ID=90

Build a Simple Gmail Notifier using Windows Forms

http://www.dotnetcurry.com/ShowArticle.aspx?ID=292

ComboBox Control Recipes

A ComboBox is a text box combined with a ListBox. The ComboBox allows users to insert text in an editing field (TextBox)  or to make a selection from a defined set of possibilities.
How Do I Get Started With The ComboBox Control
 
A ComboBox is a text box combined with a ListBox. The ComboBox allows users to insert text in an editing field (TextBox)  or to make a selection from a defined set of possibilities.
The DropDownStyle property in the Appearance section of the properties window determines the style of the ComboBox. The default value is set to DropDown which means the text portion is editable and thus you can type any value in the editable area of the ComboBox. If you set the DropDownStyle property to DropDownList, The user cannot directly edit the text portion. You can select only valid values from the list. Setting it to simple makes The text portion editable. The list portion is always visible.
To add objects to the list at run time, assign an array of object references with the AddRange method. The list then displays the default string value for each object. You can add individual objects with the Add method.
The following code example shows how you can create a ComboBox programmatically by setting a few properties. It uses the AddRange method to add items to a ComboBox. The code also adds an event handler which is currently left for the users to implement.
 
// ComboBox cmb;
// System.Object[] ItemRange;
 
private void CreateComboBox()
{
cmb = new ComboBox();
cmb.Location = new Point(12,30);
cmb.Size = new Size(168,20);
cmb.DropDownWidth = 150;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
AddItems();
Controls.Add(cmb);
 
}
 
private void AddItems()
{
ItemRange = new System.Object[5];
for (int i = 0; i <= 4; i++)
{
ItemRange[i] = "Item " + i;
}
cmb.Items.AddRange(ItemRange);
}
 
// Currently an empty implementation of the IndexChanged Event handler
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
{
      // Add Your Code here
}
 
How Do I Add/Remove Items From A ComboBox
 
The ComboBox.Items property enables you to obtain a reference to the list of items that are currently stored in the ComboBox. With this reference, you can add items, remove items, and obtain a count of the items in the collection
 
Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources. The items displayed are usually strings; however, any object can be used.
 
I have already demonstrated how to add a range of items in the previous section 4.1 using AddItems() method. Let me demonstrate how to add/remove individual items.
 
The following example requires two buttons (btnAddItems and btnRemoveItems) to be placed on the form.
 
// Add individual items
private void btnAddItems_Click(object sender, EventArgs e)
{
// To insert at last position
int cnt = cmb.Items.Count;
 
if (txtItems.Text != String.Empty)
{
cmb.Items.Insert(cnt,txtItems.Text);
}
else
{
cmb.Items.Insert(cnt, "Item " + cnt);
}
 
txtItems.Text = ""; // Emtpy text box after addition
}
 
 
 
// To remove individual items
private void btnRemoveItems_Click(object sender, EventArgs e)
{
cmb.Items.Remove(cmb.SelectedItem);
 
// To remove item at a specified index, use RemoveAt
// cmb.Items.RemoveAt(0);
 
}
 
Note : To Remove all items in the combobox, use cmb.Items.Clear()
 
How Do I Search An Item In the ComboBox Control
 
The ComboBox.FindStringExact Method finds the first item in the combo box that matches the specified string. The return value is the zero-based index of the first item found. In case of no match is found, it returns -1. The parameter passed to this method is a string which is compared against the text associated with the items in the combo box list. The search looks for a match starting from the beginning of the text, returning the first item in the list that matches the specified substring. There also exists a FindStringExact(String, Int32) method which takes a string as well as an integer as parameters. This method is used to find the first item after the specified index that matches the specified string.
 
Note : The search performed by this method is not case-sensitive.
The following code example demonstrates how to use the FindStringExact methods to search the ComboBox. To run the example, enter the text to be searched in a TextBox named txtItems and call theFindStringInCombo() method in the form's btnSearchComboBox_Click Event.
 
private void btnSearchComboBox_Click(object sender, EventArgs e)
{
FindStringInCombo();
}
 
private void FindStringInCombo()
{
 
int res = -1;
 
if (txtItems.Text != String.Empty)
{
// FindStringExact method Finds the first
// occurrence in the list.
res = cmb.FindStringExact(txtItems.Text);
 
      // FindStringExact returns -1 if string not found
if (res != -1)
{
MessageBox.Show(String.Format("The string {0} was found at position {1}", txtItems.Text, res));
cmb.SelectedIndex = res;
}
else
{
MessageBox.Show("The string you supplied is not present in the list");
}
}
else
{
MessageBox.Show("Enter a String to Search","Search String not supplied");
txtItems.Focus();
}
 
}
 
How Do I Create An AutoComplete ComboBox
 
The Visual Studio .NET 2005 brings autocomplete to the mainstream WinForms development. This capability was added manually in previous versions of .NET, but is now built in. In .NET 2.0 there is a new property on the ComboBox that sets an option that controls how automatic completion works for the ComboBox. The values available for this property are Append, Suggest, SuggestAppend, and None. The default is None.
 
The following example demonstrates how to add the autocomplete feature to a ComboBox. To implement this, set ComboBox.DropDownStyle to DropDown and ComboBox.AutoCompleteMode to either Append/Suggest/SuggestAppend.
 
If you require the drop down list to show up automatically when the user starts typing, then you can cause the Combobox to drop down by setting its DroppedDown property = true.
 
In the CreateComboBox(), add these following lines of code:
 
// Add these lines to enable AutoComplete
cmb.DropDownStyle = ComboBoxStyle.DropDown;
cmb.AutoCompleteMode = AutoCompleteMode.Append;
cmb.KeyPress += new KeyPressEventHandler(cmb_KeyPress);
 
Add an event handler to cause the ComboBox to dropdown once the user starts typing.
 
private void cmb_KeyPress(object sender, KeyPressEventArgs e)
{
//To enable the comboBox to drop.
cmb.DroppedDown = true;
}
 
How Do I OwnerDraw A ComboBox
 
The ComboBox.DrawMode property sets a value that is used to specify if a control is drawn by the operating system or if your own code handles the drawing of the control. These DrawMode enumeration values are:
 
Normal - All the elements in a control are drawn by the operating system and are of the same size. 
 
OwnerDrawFixed - All the elements in the control are drawn manually and are of the same size. 
 
OwnerDrawVariable - All the elements in the control are drawn manually and can differ in size. 
 
To perform the drawing of each item into the ComboBox, you use the DrawItem event. You can use this event to specify the tasks needed to draw items in the ComboBox.
 
The following example demonstrates how to create owner-drawn ComboBox items. The code uses the DrawMode property to specify that the items drawn are OwnerDrawFixed. The DrawItem event performs the drawing of each item into the ComboBox.
 
In the CreateComboBox() method, add these two lines of code :
 
// Owner Draw
cmb.DrawMode = DrawMode.OwnerDrawFixed;
cmb.DrawItem += new DrawItemEventHandler(cmb_DrawItem);
 
 
// Custom Owner Draw
private void cmb_DrawItem(object sender, DrawItemEventArgs e)
{
System.Drawing.Font fFont;
FontFamily fFamily = null;
FontStyle style = FontStyle.Bold;
float fontsize = 0;
 
System.Drawing.Color clr = new System.Drawing.Color();
switch (e.Index)
{
case 0:
fontsize = 8;
clr = Color.Gray;
fFamily = FontFamily.GenericSansSerif;
style = FontStyle.Bold;
break;
case 1:
fontsize = 9;
clr = Color.Gray;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Italic;
break;
case 2:
fontsize = 10;
clr = Color.Tan;
fFamily = FontFamily.GenericSansSerif;
style = FontStyle.Regular;
break;
case 3:
fontsize = 11;
clr = Color.DarkRed;
fFamily = FontFamily.GenericSerif;
style = FontStyle.Regular;
break;
case 4:
fontsize = 12;
clr = Color.Fuchsia;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Strikeout;
break;
}
 
// Draw the background of the item.
e.DrawBackground();
 
// Displays a rectangle of different colors
Rectangle rectangle = new Rectangle(4, e.Bounds.Top + 3,
e.Bounds.Height, e.Bounds.Height - 8);
e.Graphics.FillRectangle(new SolidBrush(clr), rectangle);
 
// Draws the specified text string in the specified rectangle
// using a different size, color, and font for each item.
fFont = new Font(fFamily, fontsize, style);
e.Graphics.DrawString((String)ItemRange[e.Index], fFont, System.Drawing.Brushes.Black, new RectangleF(e.Bounds.X + rectangle.Width, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
 
// Draw the focus rectangle if the mouse hovers over an item.
e.DrawFocusRectangle();
}
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the ComboBox Control. I hope this article was useful and I thank you for viewing it.

How to run only a Single Instance of the Application using Windows Forms

If you are looking out for a quick solution to prevent the user from opening up multiple instances of the application, this article is was for you. We will explore how to use Mutex to check for the running instance of the application and prevent creation of multiple instances.
Mutex is a synchronization mechanism that prevents simultaneous use of a common resource, by multiple threads. When multiple threads access a shared resource, Mutex grants the access to only one thread at a time. It is only after the first thread releases the Mutex, the second thread is able to take access to the resource.  Let us see how we can use Mutex to open up only one instance of the application at a time. Follow these steps:
Step 1: Create a new windows form project and open the Program.cs file. The code will be similar to the following:
C#
   static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
VB.NET
   Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Private Sub New()
            End Sub
            <STAThread> _
            Shared Sub Main()
                  Application.EnableVisualStyles()
                  Application.SetCompatibleTextRenderingDefault(False)
                  Application.Run(New Form1())
            End Sub
   End Class
Step 2: We will change the code shown above to use Mutex and restrict the access to the form creation to a single thread. This will in turn force other threads to wait until the Mutex is released by the owner thread.
When you initialize a Mutex, you can assign it a name and a Boolean value(to its constructor). The Boolean value determines if the calling thread takes over the ownership of the Mutex. So the first time the application starts, the variable ‘instanceCountOne’ is set to true to indicate that the calling thread has taken over the ownership.
Now the next time, when the user attempts to run the application again, the name ‘MyRunningApp’ is checked to see if the Mutex already exists at the time of the Mutex initialization. If the name exists, then that Mutex object instance is returned. So the variable ‘instanceCountOne’ remains false and thus the user gets a message stating “An application instance is already running”
Here’s how the code will look like:
C#
   static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            bool instanceCountOne = false;
 
            using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
            {
                if (instanceCountOne)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    mtex.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("An application instance is already running");
                }
            }
        }
    }
VB.NET
   Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Private Sub New()
            End Sub
            <STAThread> _
            Shared Sub Main()
                  Dim instanceCountOne As Boolean = False
 
                  Using mtex As Mutex = New Mutex(True, "MyRunningApp", instanceCountOne)
                        If instanceCountOne Then
                              Application.EnableVisualStyles()
                              Application.SetCompatibleTextRenderingDefault(False)
                              Application.Run(New Form1())
                              mtex.ReleaseMutex()
                        Else
                              MessageBox.Show("An application instance is already running")
                        End If
                  End Using
            End Sub
   End Class
Well that’s it. Using the code shown above, you can now prevent multiple instances of the application from running. Just a word of caution though. The process of checking up the mutex name can be a little time consuming.I hope this article was useful and I thank you for viewing it.

Categories

Recent posts