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
Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
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...
Japan DX Pavilion at @CloudEXPO Silicon Valley
The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
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...
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...
Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...