Make events to menus (C#)

In this post I will show you how make events to menu
  1. Goto Toolbox and drag and drop a TabControl
  2. We need a plain tabb. Because right click on middle of the tabb and select Delete
  3. Delete default two tabbs
  4. Click on tabb and go to Propeties -> Dock -> Fill
  5. Double click on the New submenu and enter this codes
                TabPage tp = new TabPage("New");
                RichTextBox rtb = new RichTextBox();
                rtb.Dock = DockStyle.Fill;
                tp.Controls.Add(rtb);
                tabControl1.TabPages.Add(tp);
        
  6. You have to make a new function for text box. here we are using RichTextbox
  7. This is code for it
  8.         private RichTextBox GetRichBox()
            {
                RichTextBox rtb = null;
                TabPage tp = tabControl1.SelectedTab;
                if(tp!=null)
                {
                    rtb = tp.Controls[0] as RichTextBox;
                }
                return rtb;
            }
        
    Now let's code the others
  9. Double click on the submenu item and enter following codes
  10. Open
    OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Text File(*.txt)|*.txt";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName);
                    GetRichBox().Text = sr.ReadToEnd();
                    sr.Close();
                }
    Save
    SaveFileDialog sfd = new SaveFileDialog();
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName);
                    sw.Write(GetRichBox().Text);
                    sw.Close();
                }
            
    Exit
    Application.Exit();
            
    Undo
    GetRichBox().Undo();
    Redo
    GetRichBox().Redo();
    Cut
    GetRichBox().Cut();
    Copy
    GetRichBox().Copy();
    Paste
    GetRichBox().Paste();
    Select All
    GetRichBox().selectAll();
  11. We can add a filter when open and save a text file.
  12. To do this add following code to Open and Save submenus
  13. Open
    ofd.Filter="Text File(*.txt)|*.txt";
                
    Save
    sfd.Filter="Text Files(*.txt)|*.txt";
                
You can see when the programm is openning there was no new tabb. To make that we can make a new function by using code we use for New menu. So make a new function and call it when programm is open . Follow the following image guids

Next post I will show you how search a word and highlight them

No comments:

Post a Comment