Microsoft Cloud Authors: Pat Romanski, Andreas Grabner, Nick Basinger, Kevin Benedict, Liz McMillan

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

C# and the .NET Framework: Tying It All Together

Part 1: Developing a Notepad-type application using C#

A co-worker of mine asked if I knew of any publications that offered a tutorial on developing an application in C# using the .NET Framework. He wanted something simple that would illustrate different techniques. He was a beginner who knew the basics but wanted to see something that would tie it all together.

This is the first in a series of articles that aim to fill that need. In this article I will show you the first steps in building a Notepad-type application that we'll call Netpad (see Figure 1). Each successive article will build upon the code from the previous article. You'll start out by learning the basic structure of a Windows Forms application, then move on to adding controls to your form, adding a menu bar, implementing file operations, and coding search/replace functions.


This article is not a tutorial on programming in C# or on using Microsoft Visual Studio .NET; it assumes you know at the least the syntax and concepts of C# and the .NET Framework. If you need to learn the basics, I recommend Introduction to C# Using .NET by Robert Oberg (from Pearson Education).

The code written in this article was tested and compiled with the Microsoft .NET Framework version 1.1. Any other dependencies will be noted where necessary.

The Goal: A Notepad Replacement
The first step in our project is to define our functionality. Our goal is simple: take every feature of the Windows Notepad application (notepad.exe) and duplicate it in Netpad. Looking at the interface and menu bar of Notepad tells us what we need to duplicate:

  • Interface functions: A window-sized, editable text box
  • File functions: Open, save, save as, print
  • Edit functions: Clipboard interface, find/replace, go to line numbers, insert current time/date
  • Format functions: Word wrap, custom font
  • View functions: Status bar (showing insert cursor position)
  • Help functions: Help and "About Netpad"
Thanks to the .NET Framework, much of this functionality will be easy to implement. In fact, by the end of this article, the editable text box and some preliminary menu options will be in place and fully functional.

The NetpadForm Class
Our main class will be called NetpadForm, a member of the SysCon.NDJ.Netpad namespace. This class inherits from System.Windows.Forms.Form - the base class that represents an application window.

In the constructor of NetpadForm, we will initialize all the objects that make up our application, including the objects that set the properties for our application window, create our TextBox control, and create our main menu.

As for the NetpadForm object itself, we will initialize the title bar text and set the initial size of the window:

this.ClientSize = new Size(400, 320);
this.Text = "Netpad";

Netpad's Core: The TextBox
The core of Netpad is the editable text box, which will be an instance of the System.Win dows.Forms.TextBox class. This instance has some specific requirements:

  • The text box must fill the entire application window, and must resize itself along with the application window.
  • The text box must allow multiple lines and a wide variety of user input.
  • The default font should be a monospaced font.
  • Scroll bars should be available.
The code to create and initialize our TextBox follows:

// Create text box
_textBox = new TextBox();
_textBox.Location = new Point(0, 0);
_textBox.Dock = DockStyle.Fill;
_textBox.Multiline = true;
_textBox.AcceptsReturn = true;
_textBox.AcceptsTab = true;
_textBox.Font = new Font( FontFamily.GenericMonospace, 9 );
_textBox.ScrollBars = ScrollBars.Both;
_textBox.Text = "";

The Dock property is intriguing - it allows you to "dock" an object to a specific edge (or edges) of its parent container. In this case, we are docking all sides of the TextBox to its parent container, which is NetpadForm (our application window). This ensures that the top, right, bottom, and left corners of the TextBox are always the same as the top, right, bottom, and left corners of our application window.

Of course we also need to add our TextBox to our window. Each window has a collection, named Controls, that stores all the controls for the window. We call the Add method for this collection, passing the _textBox field to add our control to the window.

this.Controls.Add( _textBox );

Building the Main Menu
There are two classes used in creating a menu, both of which are part of the System.Windows. Forms namespace: MainMenu and Menu Item. The process of creating a menu is relatively simple:

  1. Create a MainMenu object.
  2. Create a MenuItem object for each top-level menu (File, Edit, etc.).
  3. Create and add each top-level menu item to the MainMenu object.
  4. Add individual menu items below each top-level MenuItem object (New, Save, Cut, Copy, etc.).
  5. Set an event handler to the menu's Clicked event.
  6. Add the MainMenu object to the window.
In coding Netpad, we will store the MainMenu object and each MenuItem object in a separate field, naming them so we can reference them easily in our code. The initial File and Edit menus we create are shown in Table 1.


Let's examine the process outlined above to create our File menu, which initially will include only one item, Exit.

Step 1: Create a MainMenu object
Set the _mainMenu field to a new MainMenu object.

_mainMenu = new MainMenu();

Step 2: Create a MenuItem object for each top-level menu
Set the _miFile field to a new MenuItem object. Note the ampersand (&) before the (F) in File; this is how you mark the ALT-shortcut key for the menu. (If you do this, users will be able open the File menu by pressing ALT-F.)

_miFile = new MenuItem( "&File" );

Step 3: Add the top-level menu item to the MainMenu object
The MainMenu class stores all menu items in a collection named MenuItems. This Menu Items collection has a method, AddMenu, that accepts a Menu Item. We pass the _miFile object to this method to add our File menu to the main menu.

_mainMenu.MenuItems.Add( _miFile );

Step 4: Create and add individual menu items below the top-level MenuItem object
This step is somewhat of a repeat of Step 2 and Step 3. First we create a new MenuItem object, in this case for our File/Exit menu item (stored in the _miFileExit field), just the way we did in Step 2. Then we add the new menu item to the top-level MenuItem object; this is why the "Exit" menu item appears under File and not in the main menu itself. Just like the MainMenu class, the MenuItem class has a collection of MenuItem objects (named MenuItems), and a method to add new MenuItem objects to the collection (named AddMenu).

_miFileExit = new MenuItem( "E&xit" );
_miFile.MenuItems.Add( _miFileExit );

Step 5: Set an event handler to the menu's Clicked event
If you run the code we have up to this point, you'll have a menu bar containing one item (File), which has one item below it (Exit). However, clicking on this doesn't do anything. To have a menu item respond to a mouse click, we need to create an event handler and set this event handler to be called when our menu item is clicked.

Event handlers are special methods that can be called in response to an event. An event can be a mouse click, a key press, a key release, an object being drawn on the screen, and so forth. Different objects can respond to different types of events. Most user interface objects can respond to a Click event - that is, a mouse click. In the case of the MenuItem, a Click event is a mouse click or a menu item selection using the keyboard (such as through a shortcut key).

Event handlers must be declared in a specific way. Examine the event handler for the Click event on the File/Exit menu item:

protected void MenuFileExit_Click( System.Object sender, System.EventArgs e )
// Exit the application

I named the event handler so that it is easy to identify - MenuFileExit_Click indicates the Click event for the File/Exit menu command. This event handler does one thing: it causes our application to quit by calling the Application.Exit() method.

To connect an event handler with an event, you must specify the following:

_miFileExit.Click += new System.EventHandler( MenuFileExit_Click );

To put all the code together to create our main menu, our File menu, and our Exit command, we use the following code:

_mainMenu = new MainMenu();
_miFile = new MenuItem( "&File" );
_mainMenu.MenuItems.Add( _miFile );
_miFileExit = new MenuItem( "E&xit" );
_miFile.MenuItems.Add( _miFileExit );
_miFileExit.Click += new System.EventHandler( MenuFileExit_Click );

Step 6: Add the MainMenu object to the window
Since a window can have only one main menu, we simply assign our _mainMenu object to the Menu property of the window.

this.Menu = _mainMenu;

Putting It Together: Netpad, Phase 1
The source code for this article, available for download from www.sys-con.com/dotnet/source.cfm, includes all the functionality to open a new, blank Netpad window in which we can type and edit our text as we choose. Furthermore, we can exit our application using the File/Exit command.

To create the Netpad executable, create a directory called Netpad on your C: drive. Put the final source code file in this directory and name it Netpad.cs. Then compile it using the .NET Framework's C# compiler program, csc.exe. It can be found in the %windir%\Microsoft.NET\Framework\v1.1.4322 directory. The syntax would be:

csc /out:c:\netpad\Netpad.exe /target:winexe c:\netpad\netpad.cs

Granted, there are some serious omissions that limit Netpad's usefulness at this point. In Part 2 of this series I will flesh out the menu bar, adding clipboard functionality and formatting options. I'll also show you how to dynamically enable and disable menu items to make your application behave just like the Windows Notepad.

In the meantime, if you have questions or comments, please send me an e-mail at [email protected]. And if you need to take a break from the action, point your Web browser to www.csfbl.com and enjoy a little online baseball.

More Stories By Brian DeMarzo

Brian DeMarzo has over 10 of years experience as a developer and systems engineer. He is an IT manager at a law firm in New York, a freelance consultant, the developer/designer of an online baseball game (www.csfbl.com), and developer and contributor to Marzie's Toolbox (www.marzie.com).

Comments (3)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...