Full Version: Creating your own Notepad App
Dream.In.Code > Programming Tutorials > C# Tutorials
gbertoli3
This is a Two-Part Tutorial on Creating and Extending the Notepadd App.

Create a Notepad App
In this tutorial I will show you how you can create your own Notepad like Application.

Start by creating a new Windows Forms Application.

Now we can add some controls. The first control will be a MenuStrip.
IPB Image

After that right click on the newly created menustrip, Select Insert Standard Items. Delete the Tools menu and the Help menu. Delete the Redo menu item from the Edit menu.

Now drag and drop a TextBox onto the form.
IPB Image

Make sure that the textbox can have more than one line, by selecting the multiline checkbox.
IPB Image

Type in txtBox for the name of our newly created textbox. Set the Dock to Fill

Now we will do some coding.

For the New menu item's Click() event type in txtBox.Clear();
For the Open menu item's Click() event type in
CODE

            //Declare open as a new OpenFileDailog
            OpenFileDialog open = new OpenFileDialog();
            //Set the Filename of the OpenFileDailog to nothing
            open.FileName = "";
            //Declare filename as a String equal to the OpenFileDialog's FileName
            String filename = open.FileName;
            //Declare filter as a String equal to our wanted OpenFileDialog Filter
            String filter = "Text Files|*.txt|All Files|*.*";
            //Set the OpenFileDialog's Filter to filter
            open.Filter = filter;
            //Set the title of the OpenFileDialog to Open
            open.Title = "Open";
            //Show the OpenFileDialog
            if (open.ShowDialog(this) == DialogResult.OK)
            {
                //Make the txtBox's Text equal to all of the text in the OpenFileDialog's FileName(filename)
                txtBox.Text = System.IO.File.ReadAllText(filename);
            }
            else
            {
                //Return
                return;
            }


For the Save and Save As menu items' Click() event type in
CODE

            //Declare save as a new SaveFileDailog
            SaveFileDialog save = new SaveFileDialog();
            //Declare filename as a String equal to the SaveFileDialog's FileName
            String filename = save.FileName;
            //Declare filter as a String equal to our wanted SaveFileDialog Filter
            String filter = "Text Files|*.txt|All Files|*.*";
            //Set the SaveFileDialog's Filter to filter
            save.Filter = filter;
            //Set the title of the SaveFileDialog to Save
            save.Title = "Save";
            //Show the SaveFileDialog
            if (save.ShowDialog(this) == DialogResult.OK)
            {
                //Write all of the text in txtBox to the specified file
                System.IO.File.WriteAllText(filename, txtBox.Text);
            }
            else
            {
                //Return
                return;
            }


After enter this code
CODE

            //Declare prntDoc as a new PrintDocument
            System.Drawing.Printing.PrintDocument prntDoc = new System.Drawing.Printing.PrintDocument();


For the Print menu items' Click() event type in
CODE

            //Declare print as a new PrintDialog
            PrintDialog print = new PrintDialog();
            //Declare prntDoc_PrintPage as a new EventHandler for prntDoc's Print Page
            prntDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(prntDoc_PrintPage);
            //Set prntDoc to the PrintDialog's Document
            print.Document = prntDoc;
            //Show the PrintDialog
            if (print.ShowDialog(this) == DialogResult.OK)
            {
                //Print the Page
                prntDoc.Print();
            }



Now enter this code right after the print item's Click() event



CODE

        private void prntDoc_PrintPage(Object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //Declare g as Graphics equal to the PrintPageEventArgs Graphics
            Graphics g = e.Graphics;
            //Draw the Text in txtBox to the Document
            g.DrawString(txtBox.Text, txtBox.Font, Brushes.Black, 0, 0);
        }


Now enter this code for the Print Preview menu item's Click() event
CODE

            //Declare preview as a new PrintPreviewDialog
            PrintPreviewDialog preview = new PrintPreviewDialog();
            //Declare prntDoc_PrintPage as a new EventHandler for prntDoc's Print Page
            prntDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(prntDoc_PrintPage);
            //Set the PrintPreview's Document equal to prntDoc
            preview.Document = prntDoc;
            //Show the PrintPreview Dialog
            if (preview.ShowDialog(this) == DialogResult.OK)
            {
                //Generate the PrintPreview
                prntDoc.Print();
            }


Now go to the Exit menu item's Click() event and type Close;
Now go to the Undo menu item's Click() event and type txtBox.Undo();
Now go to the Cut menu item's Click() event and type txtBox.Cut();
Now go to the Copy menu item's Click() event and type txtBox.Copy();
Now go to the Paste menu item's Click() event and type txtBox.Paste();
Now go to the Select All menu item's Click() event and type txtBox.SelectAll();

Finished!

Don't forget I have included the source files: Click to view attachment

Extend the Notepad App

In this tutorial I will show you how to extend your notepad app we created in my tutorial. If you have not read my tutorial then click here.

We will add some Menu items to the MenuStrip. The first Item will we a new Menu Drop Down called Format.
In the format Drop Down Menu add a menu item called Word Wrap. Set the Checked Property to true, set the CheckOnClick Property to true. Now select the TextBox(txtBox) and set the WordWrap property to true.

Now go back to the Format menu and add one more menu item call it Font.
Drag a FontDialog onto the Form, call it fontDialog
IPB Image

Go to the Font menu item's Click() event and type
CODE

            fontDialog.ShowColor = true;
            fontDialog.ShowEffects = true;
            if (fontDialog.ShowDialog(this) == DialogResult.OK)
            {
                txtBox.ForeColor = fontDialog.Color;
                txtBox.Font = fontDialog.Font;
            }


Now we will add some shortcut keys.
For the New menu item's shortcut key type in Ctrl+N
For the Open menu item's shortcut key type in Ctrl+O
For the Save menu item's shortcut key type in Ctrl+S
For the Save As menu item's shortcut key type in Ctrl+Shift+S
For the Print menu item's shortcut key type in Ctrl+P
For the Print Preview menu item's shortcut key type in Ctrl+Shift+P
For the Undo menu item's shortcut key type in Ctrl+Z
For the Cut menu item's shortcut key type in Ctrl+X
For the Copy menu item's shortcut key type in Ctrl+C
For the Paste menu item's shortcut key type in Ctrl+V
For the Select All menu item's shortcut key type in Ctrl+A
For the Font menu item's shortcut key type in Alt+F


Now we will add a StatusStrip()
IPB Image

Make sure that it is docked to the bottom, then Right Click on txtBox and select Bring to Front.

Now add a StatusLabel to the StatusStrip by selecting the small arrow on the StatusStrip, call it statusLabel.

Now go to the txtBox's TextChanged() event and type
CODE

            Int32 lines = txtBox.Lines.Length;
            Int32 textLength = txtBox.Text.Length;
            statusLabel.Text = "Lines: " + lines + " Characters: " + textLength;


Now paste that in the Form's Load() event as well.

Now go to the Word Wrap menu item's Click() event and type
CODE

            txtBox.WordWrap = wordWrapToolStripMenuItem.Checked;
            wordWrapToolStripMenuItem.Checked = txtBox.WordWrap;


Finished!

Don't forget that I have included the source files Click to view attachment
c.v.burgess
i get an error "file name cannot be empty" when opening or saving in yoUR app and mine. What's the problem?
gbertoli3
I don't know can you post a screenshot of the ErrorMsg
c.v.burgess
Click to view attachment
gbertoli3
What were you doing to get that message?
c.v.burgess
Click to view attachment

that is opening a file
gbertoli3
That's Weird!

Did you make sure that the file exists.

Go to the openFileDialog's Properties and make sure the CheckFileExists Items is set to True
c.v.burgess
QUOTE(gbertoli3 @ 20 Sep, 2008 - 01:30 PM) *

That's Weird!

Did you make sure that the file exists.

Go to the openFileDialog's Properties and make sure the CheckFileExists Items is set to True

i did
gbertoli3
That's really weird. Did you make any modifications to the project?
c.v.burgess
QUOTE(gbertoli3 @ 20 Sep, 2008 - 01:48 PM) *

That's really weird. Did you make any modifications to the project?

none WHATSOEVER
gbertoli3
That is really weird because it works for me fine. The only thing I can think of doing is redownload the project.
c.v.burgess
this works for me (save file)
CODE
private void button1_Click(object sender, System.EventArgs e)
{
     Stream myStream;
     SaveFileDialog saveFileDialog1 = new SaveFileDialog();

     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
     saveFileDialog1.FilterIndex = 2;
     saveFileDialog1.RestoreDirectory = true;

     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         if((myStream = saveFileDialog1.OpenFile()) != null)
         {
             // Code to write the stream goes here.
             myStream.Close();
         }
     }
}


but will u tell me what to put for "//Code to write the strream goes here"? thank you
c.v.burgess
this is open
CODE
{
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

what do i do to read the stream?
c.v.burgess
HEY! how could you print with a 1/2 inch margin?
gbertoli3
Post your questions in the Forum, with the code you already have.
wingot
QUOTE(gbertoli3 @ 20 Sep, 2008 - 02:11 PM) *

That is really weird because it works for me fine. The only thing I can think of doing is redownload the project.


The problem looks like this piece of code in your tutorial:

CODE

            //Set the Filename of the OpenFileDailog to nothing
            open.FileName = "";
            //Declare filename as a String equal to the OpenFileDialog's FileName
            String filename = open.FileName;


You're first setting the FileName property to "" then assigning it to the filename string (so filename will always equal ""). You aren't then setting the filename after showing the dialogue. Of course, this means that when it tries to open "filename", it tries to open "", hence the exception stating "Empty path name is not legal".

Changing it to this will work:

CODE

            //Declare open as a new OpenFileDailog
            OpenFileDialog open = new OpenFileDialog();
            //Set the Filename of the OpenFileDailog to nothing
            open.FileName = "";
            //Declare filename as a String equal to the OpenFileDialog's FileName
            String filename = open.FileName;
            //Declare filter as a String equal to our wanted OpenFileDialog Filter
            String filter = "Text Files|*.txt|All Files|*.*";
            //Set the OpenFileDialog's Filter to filter
            open.Filter = filter;
            //Set the title of the OpenFileDialog to Open
            open.Title = "Open";
            //Show the OpenFileDialog
            if (open.ShowDialog(this) == DialogResult.OK)
            {
                // Set the filename to the dialogues value
                filename = open.Filename;
                //Make the txtBox's Text equal to all of the text in the OpenFileDialog's FileName(filename)
                txtBox.Text = System.IO.File.ReadAllText(filename);
            }
            else
            {
                //Return
                return;
            }


All I've done of course is add "filename = open.Filename;" into the if before actually trying to open the file.
wingot
Also, I've refactored your tutorial code to be more in keeping with good practice (not duplicating the same code in multiple methods for example). Adds a couple of extra functions, but makes the code both less redundant and more readable.

I also modified the saveToolStripMenuItem_Click event so that if a filename was already selected (from a previous "Save As" or "Open" operation) then this would be used (which is more in keeping with the nature of the Save option in any other program). It seemed a bit redundant and incorrect to have it doing the exact same work as the save as.

Finally, I modified the word wrap functionality slightly so that if word wrap is on the horizontal scrollbar will not display and vice-versa.

I added an about dialogue just for the sake of it too.

Of course, given that this is meant to be a tutorial this sort of thing is unneccessary, but even so, feel free to take a look at the attached code if you want.

NOTE: The attached code was created in VS2008, so the solution file may not work in VS2005.

EDIT: Added fix so that "New" option also clears the filename.
whitefish
for the problem of "Empty path name is not legal"
Change the following code from:-
CODE

this.txtBox.Text = System.IO.File.ReadAllText(filename);


to this:-
CODE

this.txtBox.Text = System.IO.File.ReadAllText(this.open.FileName);


The problem here was that the string filename was predefined with empty string and didnt have been changed after the user selected the file in the openFileDialog object. So, to solve it the best way was to take the file name from the object file (open) it self.

I didn't checked the save file yet so sorry.


Edit: sorry I didn't checked the last posts of the member before posting mine, so please forgive me
DOOMDUDE
QUOTE(c.v.burgess @ 20 Sep, 2008 - 12:25 PM) *

i get an error "file name cannot be empty" when opening or saving in yoUR app and mine. What's the problem?


i got the same error and i managed to fix it...

i think the problem is that the filename is checked too soon and that you have to move it so it is checked when the user presses ok... in other words the original code:

//Declare open as a new OpenFileDailog
OpenFileDialog open = new OpenFileDialog();
//Set the Filename of the OpenFileDailog to nothing
open.FileName = "";
//Declare filename as a String equal to the OpenFileDialog's FileName
String filename = open.FileName;
//Declare filter as a String equal to our wanted OpenFileDialog Filter
String filter = "Text Files|*.txt|All Files|*.*";
//Set the OpenFileDialog's Filter to filter
open.Filter = filter;
//Set the title of the OpenFileDialog to Open
open.Title = "Open";
//Show the OpenFileDialog
if (open.ShowDialog(this) == DialogResult.OK)
{
//Make the txtBox's Text equal to all of the text in the OpenFileDialog's FileName(filename)
txtBox.Text = System.IO.File.ReadAllText(filename);
}
else
{
//Return
return;
}

has to be changed to:

//Declare open as a new OpenFileDailog
OpenFileDialog open = new OpenFileDialog();
//Set the Filename of the OpenFileDailog to nothing
open.FileName = "";

//Declare filter as a String equal to our wanted OpenFileDialog Filter
String filter = "Text Files|*.txt|All Files|*.*";
//Set the OpenFileDialog's Filter to filter
open.Filter = filter;
//Set the title of the OpenFileDialog to Open
open.Title = "Open";
//Show the OpenFileDialog
if (open.ShowDialog(this) == DialogResult.OK)
{
//Declare filename as a String equal to the OpenFileDialog's FileName
String filename = open.FileName;
//Make the txtBox's Text equal to all of the text in the OpenFileDialog's FileName(filename)
txtBox.Text = System.IO.File.ReadAllText(filename);
}
else
{
//Return
return;
}



the same applies to the save dialog because i got the same error there...
gbertoli3
Yes, sorry about that. I guess I didn't even realize it.
Zooms
I got about 6 errors:

The name 'prntDoc' does not exist in the current context.


The code where the error is:

CODE
private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Declare print as a new PrintDialog
            PrintDialog print = new PrintDialog();
            //Declare prntDoc_PrintPage as a new EventHandler for prntDoc's Print Page
            prntDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(prntDoc_PrintPage);
            //Set prntDoc to the PrintDialog's Document
            print.Document = prntDoc;
            //Show the PrintDialog
            if (print.ShowDialog(this) == DialogResult.OK)
            {
                //Print the Page
                prntDoc.Print();
            }
        }


And in the Printpreview.
wingot
QUOTE(Zooms @ 21 Dec, 2008 - 05:16 AM) *

I got about 6 errors:

The name 'prntDoc' does not exist in the current context.

*snip*

And in the Printpreview.


You want something like this in the constructor of the form:
CODE

prntDoc = new System.Drawing.Printing.PrintDocument();
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.