Welcome!

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
Application.Exit();
}

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

Conclusion
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
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
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...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. 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 settl...
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.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...