Building a simple Notepad Windows Application
http://www.csharpfriends.com
World's Greatest C# Community    
Home Articles C# Forums Books C# Syntax C# Spec C# Jobs free Source Code Advertise About
 

Control Panel

[ Sign In / register ]
Points   
Notes 
My Forums
My Tutorials
My Profile

Resources

Learn
 Articles
 QuickStarts
 C# Spec
 Whitepapers
 Tools
 Class Browser
 C# Code Generator
 Links
 Misc Rss Feeds
 Code Highlight
 411 Directory
 FREE magazines
 freevb.net

Reviews
  ASP.NET Hosting

Source Code
 Get Version 1.0



C# Consulting
AspDotNetStoreFront
Chapter:   UnCategorized
Current Lesson:
Building a simple Notepad Windows Application
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Selecting a Random Row From a Database [next Lesson]  String Methods Implementation
Building a simple Notepad Windows Application
  by: mosessaur

Building a simple Notepad Windows Application

by: mosessaur

Introduction: Notepad is a simple windows application that apply editing text files (.txt). This simple application learn us how to create new file and write some text to it, Open an existing file and editing it.

Also we will see how to apply some text formats to the editing text area like font-family, size & style.

What should you know before start this Tutorial?

Simply how to build a simple windows application, using textBox, MainMenu controls.

Classes that will be used:

Control classes [from the toolbox]:

MainMenu & MenuItem: to choose the action from the menu like create new document, open existing document etc...

TextBox: This is the text editor area.

OpenFileDialog: to use the open file dialog to choose an existing file.

SaveFileDialog: to save the file we create.

FontDialog: to apply the font styles to our text.

StreamWriter: This Class will name the namespace System.IO, & will be used to write to the file.

StreamReader: This Class will name the namespace System.IO, & will be used to read from the file.



Coding Time:

1st Step:

After create form that will hold our notepad, we need to provide some menuItems to our main menu:

File

-->New

--->Open...

--> Save *this will be disabled when the application starts

-->Save As...



Edit

-->Cut

-->Copy

-->Paste

-->Select All



Format

-->Font...



We will implement the Click event for all submenus



You can set the Propeties of OpenFileDialog, SaveFileDialog or FontDialog from the property window if you build them from the ToolBox just drag and drop them in the form from the ToolBox.

For the FontDialog object you can set the ShowEffects Property to false, this will not display the the underline and strikout check boxes in the dialog, also you can leave the default property setting.

2nd Step

We will need to declare the following member fields:
//used when create new document to add a number to the document name like
//"myDoc0.txt", so when you create another one it will be "myDoc1.txt"
private int m_intDocNumber = 0;

//Hold the file name that created or choosed
//for the Save action, not "Save As..."
private string m_strFileName = "";

//Hold the DialogResult enum result
//Ok or Cancel
private DialogResult dlgResult;

//Stream to write to the file
private StreamWriter m_sw;

//Check if the file is modified or not
private bool m_bModified = false;
3rd Step

Implemeting the event handlers for all menu items and when the text changed, Let's start with TextChanged event, we only need to say that the original text is modified so when the user intend to close the file or open new file a message box apear to him to notify him if he would like to save his changes or not.
//The TextChanged Event for the txtBody Control
private void txtBody_TextChanged(object sender, System.EventArgs e)
{
    m_bModified = true; //Document has been modified.
}
We call the next Method to check if the text modified or not, there are 3 cases to call this method:

1-When trying to create new document while working on another one, so the user may want to save his old work before creating new one

2-When trying to open an existing document working on another one, so the user may want to save his old work before opening the existing document.

3-When Clsoing the application while the current document not saved.
//This Method check if the Text has beed modified or not
//if yes display a message asking if the user wants to save his work or not
private void CheckChanged(object sender, System.EventArgs e)
{
    if(m_bModified)
    {
        dlgResult = MessageBox.Show("Do you want to 
save?","Note",MessageBoxButtons.YesNo,MessageBoxIcon.Exclamation);
        if(dlgResult == DialogResult.Yes)
        {
            //Calling the menuItemSave_Click Mthod
                        // to save the current work document
            menuItemSave_Click(sender,e);
        }
    }
}
Now we want to create new document by using New menuItem:
private void menuItemNew_Click(object sender, System.EventArgs e)
{
        // Check if the current work document is not 
        // completely saved.

        CheckChanged(sender,e);    
        // cleare the file name so when click on Save menu Item 
        // it will not overwrite an old document

        m_strFileName = "";     

        // cleare the editor area.
        txtBody.Clear(); 
    
        // new document means not modified yet.    
        m_bModified = false; 
        
        /*

        do not replace the m_bModified position in this method
    beacuse Clear() Method invoke the TextChanged event
    */

}
Saving our work:
//Save As...
private void menuItemSaveAs_Click(object sender, System.EventArgs e)
{
    //dlgSaveFile is a SaveFileDialog object created from the toolbox
        //like mydoc0.txt
    dlgSaveFile.FileName = "mydoc" + m_intDocNumber.ToString() + ".txt"; 
    dlgResult = dlgSaveFile.ShowDialog();

    if(dlgResult == DialogResult.Cancel)
        return;

    try
    {
                // Saving our file name for Quick Save
        m_strFileName = dlgSaveFile.FileName; 
                //Create new StreamWriter to write the text to it
        m_sw = new StreamWriter(m_strFileName); 
        m_sw.Write (txtBody.Text);
                // don't forget to close your resources after finishing 
                // using them
        m_sw.Close(); 
        menuItemSave.Enabled = true;
                
                //increasing document number;
        m_intDocNumber++; 
        m_bModified = false; //document is saved
        this.Text = "C# Simple Notepad: " + m_strFileName;
    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error",
                               MessageBoxButtons.OK,MessageBoxIcon.Error);
    }
}
//Save
private void menuItemSave_Click(object sender, System.EventArgs e)
{
    //Check if for the file name to save on the current working document or 
create new one
    if(m_strFileName == "")
    {
        //Create new one
        menuItemSaveAs_Click(sender,e);
        return;
    }
    else
    {
        //Save on the current document
        m_sw = new StreamWriter(m_strFileName);
        m_sw.Write (txtBody.Text);
        m_sw.Close();
    }
    m_bModified = false;
}
Open an Existing document when choose Open menu Item
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
    //Check if the current document is modified to save it
    CheckChanged(sender,e);

    // dlgOpenFile is an OpenFileDialog object
    dlgResult = dlgOpenFile.ShowDialog();
    if(dlgResult == DialogResult.Cancel)
        return;

    try
    {
                // get the file name
        m_strFileName = dlgOpenFile.FileName; 
                // open to read that file
        StreamReader sr = new StreamReader(m_strFileName); 
                //read the whole file
        txtBody.Text = sr.ReadToEnd();
        sr.Close();
        m_bModified = false;
    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error",
                         MessageBoxButtons.OK,MessageBoxIcon.Error);
    }
}

Now we want to change the font and its size & style:
private void menuItemFont_Click(object sender, System.EventArgs e)
{
    //dlgFont is an FontDialog object
    dlgResult = dlgFont.ShowDialog();
    if(dlgResult == DialogResult.Cancel)
        return;

        // this property will return FontFamily selected from
        // the FontDialog
    FontFamily fmFontName = dlgFont.Font.FontFamily; 
    // this property will return float 
    // Font-size selected from the FontDialog
    float fFontSize = dlgFont.Font.Size; 
    // this property will return 
    // FontStyle selected from the FontDialog
    FontStyle fsStyle = dlgFont.Font.Style; 
    Font font;
    try
    {
        //create new font and apply it to the text in txtBody
        font = new Font(fmFontName,fFontSize,
                                    txtBody.Font.Style ^ fsStyle);
        txtBody.Font = font;
    }
    catch(ArgumentException)
    {
        return;
    }
}
There are another menu items like cut, copy etc..., those are so easy and also added on a context menu that is related to the txtBody control. You can check for the whole code attached to this tutorial.

Download the complete source code

MyNotePad project & code

1 


Build Your Own ASP.NET Website Using C# & VB.NET

Chapter:  UnCategorized
Current Lesson:
Building a simple Notepad Windows Application
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Selecting a Random Row From a Database [next Lesson]  String Methods Implementation


Today's Top Movers
vulpes 6800
MadHatter 2220
jal 867
Jeff1203 857
muster 791

Yesterday Top Movers
shakti sin.. 9
MadHatter 3
C#fanatic 2
Al_Pennywo.. 2
GazzaJ 1

Monthly Leaders
vulpes 6800
MadHatter 2260
jal 867
Jeff1203 857
muster 791

Top Members
mosessaur 18457
Rincewind 7074
stanleytan 6995
vulpes 6800
Gsuttie 6046

Great Offers
.net hosting
Go To My Pc
Remote Pc Control
zonealarm
spam blocker
web hosting directory
ad server   C#
snadtech GoToMyPc

Top of Page

Advertise | About | Link To Us | Privacy Notice Copyright © 2003 - 2005 CSharpFriends.com  All Rights Reserved  Visual C# Developer Center