Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

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
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...