Give Your Forms a Base

Give Your Forms a Base

reat Windows applications have a consistent user interface. As users learn how to work with one form in the application, they can leverage that knowledge to work with other forms in the application. This both minimizes the requirements for end-user training and support and maximizes end-user satisfaction.

You can achieve a consistent feel throughout your user interface by building your own base form class. In this base form class you can write the code for all of the standard user interaction features. Every form in the application that inherits from your base form class will automatically support any feature defined in the base form class.

Creating the Base Form Class
You create a base form class the same way you create any form in a Windows application; just add a new form to a Windows Application project. Giving the base form class a clear name, such as eOrderOnLineWinBase, will help you keep track of the base form class.

You may or may not want to add controls to this base form class. If there are common UI elements on many of the forms of your application, such as a particular icon or set of buttons, then it is useful to add these to the base form class. Common UI elements in the base form class then appear on every form that inherits from the base form class, a technique referred to as visual inheritance. Frequently, however, you may find that your forms don’t have common UI elements, so it is not desirable to add common controls in fixed positions to your base form class.

You should add event handlers to the base form class to handle form and control events consistently on any form that inherits from the base form class. By leveraging the code in the base form, you minimize the amount of repetitive code in the forms.

Add event handlers to the base form class to handle form and control events consistently on any form that inherits from the base form class.

For example, to give the user a visual indicator of the control that has focus, you can change the background color of the active control on the form. To be consistent, every form should incorporate the same technique. You could add the code to handle the Enter and Leave events of every control to every form in your application; but this could require a significant amount of code since a Windows application of any significant size can require 50 or more forms. It makes more sense to write this code one time and then reuse it from every form in your application.

Defining the Event Handlers
To begin, create ProcessEnter and ProcessLeave event handlers for your new base form class. The ProcessEnter handler changes the background color of a textbox to a wheat color (light tan) and the ProcessLeave handler changes the background color back to the standard Window color. You can modify these handlers to process other types of controls as well.

In VB.NET:

   Private Sub ProcessEnter(ByVal sender As Object, _      ByVal e As System.EventArgs)      DirectCast(sender, TextBox).BackColor = _         Color.Wheat   End Sub      Private Sub ProcessLeave(ByVal sender As Object, _      ByVal e As System.EventArgs)      DirectCast(sender, TextBox).BackColor = _         Color.FromKnownColor(KnownColor.Window)   End Sub

In C#:

   private void ProcessEnter(object sender,       System.EventArgs e)   {       ((TextBox)sender).BackColor = Color.Wheat;   }   private void ProcessLeave(object sender,       System.EventArgs e)   {      ((TextBox)sender).BackColor =       Color.FromKnownColor(KnownColor.Window);   }

Next, you need a way to “wire up” all of the textbox controls on a form to the ProcessEnter and ProcessLeave events when your application loads your form. You could do this by adding code to the Load event on each form, but adding it to the base form class means that you don’t need to repeat the code. In addition, as you add forms to the application, you don’t need to remember to wire up the events.

To inherit from the base form class from any form in your application, you simply change the class declaration for the form.

The base form loads automatically when an inherited form loads. So the best place to put the code to “wire up” the event handler is in the Load event of the base form class:

In VB.NET:

   Private Sub eOrderOnLineWinBase_Load(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles MyBase.Load      SetEventHandlers(Me)   End Sub

In C#:

   private void eOrderOnLineWinBase_Load(object      sender, System.EventArgs e)   {      SetEventHandlers(this);   }

In this snippet, Me (VB.NET) or this (C#) refers to the currently running instance, which is the instance of the form that inherits from this base form class, commonly called a child form.

The SetEventHandlers method iterates through the Controls collection of the child form, which is no easy task since the Controls collection is hierarchical. The first level of the Controls collection hierarchy includes only the controls directly on the form. The second level of the hierarchy includes the controls that are contained in any of the controls that are directly on the form.

An example may clarify this concept. Say you have a form with two panels on it: pnlSelection and pnlInformation. In pnlSelection you have a combo box that allows the user to select an entry. In pnlInformation you have a tab control. The tab control contains two tab pages and on each tab page you have sets of controls that include textbox controls. If you looked at the Controls collection for the form you would see that the collection only contains two controls: pnlSelection and pnlInformation. These are the only two controls in this example that are directly on the form.

To access the controls contained in pnlSelection, you have to access the Controls collection for pnlSelection. To access the controls on the tab control on pnlInformation, you have to access the Controls collection for pnlInformation (which contains the tab control), the Controls collection for the tab control (which contains the tab pages), and then the Controls collection of each of the tab pages (which contains the text boxes).

To write a function that accesses all of the controls on the form in a generic fashion, you need to write a function that is recursive, meaning that it calls itself. The function iterates through the Controls collection and, if it finds a control in the Controls collection that contains other controls (referred to as child controls), the function will call itself to iterate through the child control’s Controls collection.

In VB.NET:

Private Sub SetEventHandlers(ByVal ctrlContainer _   As Control)      Dim ctrl As Control      For Each ctrl In ctrlContainer.Controls         If TypeOf ctrl Is TextBox Then            AddHandler ctrl.Enter, _               AddressOf ProcessEnter            AddHandler ctrl.Leave, _               AddressOf ProcessLeave         End If         If ctrl.HasChildren Then            SetEventHandlers(ctrl)         End If      Next   End Sub

In C#:

   private void SetEventHandlers(Control      ctrlContainer)   {      foreach (Control ctrl in ctrlContainer.Controls)      {         if (ctrl is TextBox)         {            ctrl.Enter +=                new System.EventHandler               (this.ProcessEnter);            ctrl.Leave +=                new System.EventHandler               (this.ProcessLeave);         }                    if (ctrl.HasChildren)         {            SetEventHandlers(ctrl);         }      }   }

This routine sets the Enter and Leave event handlers for all of the textbox fields of the form, even if the textbox is contained within another control. The AddHandler statement (VB.NET) or EventHandler (C#) defines the event handler to call when the event occurs. In this example, the code will call the ProcessEnter method when a textbox generates an Enter event (the user enters a control) and the ProcessLeave method when a textbox generates a Leave event (the user leaves a control).

You can add any other event handlers to this base form class. For example, you could handle the Initialize event for a grid to set up a standard grid look (border colors and styles, header colors and styles, and so on). You could even handle the Validating event to perform standardized validation for the controls on all of the forms in the application.

Inheriting from the Base Form Class
The only remaining step involves using the base form class in any form that needs the standard user interface behavior.

To inherit from the base form class from any form in your application, you simply change the class declaration for the form as follows:

In VB.NET:

   Public Class LoginWin      Inherits eOrderOnLineWinBase

In C#:

   public class LoginWin : eOrderOnLineWinBase

When the user enters a textbox on any form that inherits from eOrderOnlineWinBase, the form will change the background color to a wheat color (light tan) allowing the user to easily see which control has focus. When the user leaves the text box, the form will change the background color back to the user’s default Windows color.

It is very tedious to write event procedure and other user-interface code in your Windows applications, especially when you have many forms in your application. By using a base form class you can write that code one time and leverage it from all of the forms in your application.

The technique described in this article provides a base form class that any form can inherit, giving your users a consistent experience and minimizing the code that you need to write.

devx-admin

devx-admin

Share the Post:

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically