Editor Form

image_pdfimage_print


/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/
using System.Windows.Forms;
using System;
using System.Drawing;
using System.IO;

namespace Chapter2App
{
public class EditorForm : System.Windows.Forms.Form
{
// The RichTextBox control
private RichTextBox richTxtBox;

// constructor
public EditorForm()
{
// Instantiate the richTextBox member
this.richTxtBox = new RichTextBox();
// Set the Dock style so that the control fills the Form
this.richTxtBox.Dock = DockStyle.Fill;
// Add the RichTextBox to the Form
this.Controls.Add(this.richTxtBox);
}

public string EditText
{
get
{
return this.richTxtBox.Text;
}
set
{
richTxtBox.Text = value;
}
}

}

public class MyForm : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu;
private ToolBar toolBar;
private StatusBar statusBar;

// constructor
public MyForm()
{
// set the title
this.Text = “Hello world”;
// set the default size
this.Size = new System.Drawing.Size(500,500);
// set make the form non resizeable with sunken edge
//this.FormBorderStyle = FormBorderStyle.Fixed3D;

// Create the menu items
MenuItem miNew = new MenuItem(“&New”,new EventHandler(OnMenuNew));
// adding a “-” titled menu item adds a divider on the menu
MenuItem miDash = new MenuItem(“-“);
MenuItem miOpen = new MenuItem(“&Open”,new EventHandler(OnMenuOpen));
MenuItem miSave = new MenuItem(“&Save”,new EventHandler(OnMenuSave));

// Create the array of menu items which will form the submenu of File
MenuItem[] fileMiArray = new MenuItem[] {miNew,miDash,miOpen,miSave};
// create the File menu Item
MenuItem miFile = new MenuItem(“&File”,fileMiArray );
// Cretat the array of menu itme for the main menu
MenuItem[] mainMiArray = new MenuItem[] {miFile};
// Create the main menu
this.mainMenu = new MainMenu(mainMiArray);

// Another way of creating MainMenu object and attaching a MenuItem
//this.mainMenu = new MainMenu();
//this.mainMenu.MenuItems.Add(miFile );

// Add the Help menu using a different route
MenuItem aboutMenuItem = new MenuItem();
aboutMenuItem.Text = “&About”;
aboutMenuItem.Click += new EventHandler(OnMenuAbout);

MenuItem helpMenuItem = new MenuItem();
helpMenuItem.Text = “&Help”;
helpMenuItem.MenuItems.Add(aboutMenuItem);

mainMenu.MenuItems.Add(helpMenuItem);

// Attach the main menu object to the form
this.Menu = this.mainMenu;

// Context Menu
//MenuItem redContext = new MenuItem(“Make Form Red”,new EventHandler(OnContextRed));
//MenuItem greyContext = new MenuItem(“Make Form Grey”,new EventHandler(OnContextGrey));

//ContextMenu colorContextMenu = new ContextMenu(new MenuItem[] {redContext,greyContext});
MenuItem colorContext = new MenuItem(“Change the color of the Form”,new EventHandler(OnContextColor));
ContextMenu colorContextMenu = new ContextMenu(new MenuItem[] {colorContext});

this.ContextMenu = colorContextMenu;

// Make this Form a MDI container
this.IsMdiContainer = true;

// Toolbar

// The ImageList of the toolbar
ImageList imageLst = new ImageList();
// Create Bitmap objects to add to the ImageList
//Bitmap bmpStrip = new Bitmap(“ToolBarStrip.bmp”);
Bitmap bmpStrip = new Bitmap(GetType(),”ToolBarStrip.bmp”);
imageLst.Images.AddStrip(bmpStrip);
imageLst.TransparentColor = Color.Red;

// Need the actual bmp files on the directory of the app!
//Bitmap bmpNew = new Bitmap(“NEW.bmp”);
//Bitmap bmpOpen = new Bitmap(“OPEN.bmp”);
//Bitmap bmpSave = new Bitmap(“SAVE.bmp”);
// Add the images created to the ImageList
//imageLst.Images.Add(bmpNew);
//imageLst.Images.Add(bmpOpen);
//imageLst.Images.Add(bmpSave);
// Set transparent color so that background dont show

// Create the ToolBar object
toolBar = new ToolBar();
// Toolbar belongs to this Form
toolBar.Parent = this;
// ImageList is the one we just created
toolBar.ImageList = imageLst;

/*
// Add 3 buttons
for(int i=0; i< 3;i++) { // Create the buttons ToolBarButton toolBtn = new ToolBarButton(); // Show the image i from the ImageList of the toolbar toolBtn.ImageIndex = i; // Add the button to the ToolBar toolBar.Buttons.Add(toolBtn); } */ // Create the buttons ToolBarButton toolBtnNew = new ToolBarButton(); ToolBarButton toolBtnOpen = new ToolBarButton(); ToolBarButton toolBtnSave = new ToolBarButton(); // Show the image i from the ImageList of the toolbar toolBtnNew.ImageIndex = 0; toolBtnOpen.ImageIndex = 1; toolBtnSave.ImageIndex = 2; // Add the appropriate menu items toolBtnNew.Tag = miNew; toolBtnOpen.Tag = miOpen; toolBtnSave.Tag = miSave; // Add the button to the ToolBar toolBar.Buttons.Add(toolBtnNew); toolBar.Buttons.Add(toolBtnOpen); toolBar.Buttons.Add(toolBtnSave); // Wire the button click handler for the toolbar toolBar.ButtonClick += new ToolBarButtonClickEventHandler(ToolBarClick); statusBar = new StatusBar(); //statusBar.Text = "I am a status bar"; statusBar.ShowPanels = true; statusBar.Parent = this; // Create and the Help panel StatusBarPanel statusPanelHelp = new StatusBarPanel(); statusPanelHelp.AutoSize = StatusBarPanelAutoSize.Spring; statusPanelHelp.Text = "This is the place for help!"; statusBar.Panels.Add(statusPanelHelp); // Create and add the Date panel StatusBarPanel statusPanelDate = new StatusBarPanel(); statusPanelDate.AutoSize = StatusBarPanelAutoSize.Contents; // Get todays date DateTime dt= DateTime.Now; statusPanelDate.Text = dt.ToShortDateString(); statusBar.Panels.Add(statusPanelDate); // Wire the Closing event to the HandleClosing method // this.Closing += new System.ComponentModel.CancelEventHandler(HandleClosing); } void ToolBarClick(object sender,ToolBarButtonClickEventArgs e) { MenuItem menuItemForButton = (MenuItem) e.Button.Tag; menuItemForButton.PerformClick(); /* // Find out which button is clicked by their position switch(toolBar.Buttons.IndexOf(e.Button)) { case 0: // First button is the New button // Call the menu handler but passing null on the 2nd param this.OnMenuNew(sender,null); break; case 1: // Second button is the Open button this.OpenDocument(); break; case 2: // Third button is the Save button this.SaveActiveDocument(); break; } */ } void OnContextColor(object obj, EventArgs e) { ColorDialog colorDlg = new ColorDialog(); if(colorDlg.ShowDialog() == DialogResult.OK) { // Grab the third child f this Form and set its color this.Controls[2].BackColor = colorDlg.Color; // Does't work after adding the status bar since the status bar becomes the second child // Grab the second child of this Form and set its color //this.Controls[1].BackColor = colorDlg.Color; // Doesn't work with toolbar, because toolbar becomes the first child: // Grab the first child control of this Form and set its color //this.Controls[0].BackColor = colorDlg.Color; } // Doesn't work for MDI container since this Form is hidden // by a new MDI child Form managing Form //this.BackColor = Color.Red; } void OnContextRed(object obj, EventArgs e) { // Grab the first child control of this Form and set its color this.Controls[1].BackColor = Color.Red; // Doesn't work for MDI container since this Form is hidden // by a new MDI child Form managing Form //this.BackColor = Color.Red; } void OnContextGrey(object obj, EventArgs e) { // Grab the first child control of this Form and set its color this.Controls[0].BackColor = Color.Gray; // Doesn't work for MDI ... //this.BackColor = Color.Gray; } void OnMenuAbout(object obj, EventArgs e) { // Forces the context menu for the main Form to pop up at // the given position. this.ContextMenu.Show(this, new Point(20,100)); } void OnMenuNew(object obj, EventArgs e) { // Instantiate our custom form and show it EditorForm editForm = new EditorForm(); editForm.MdiParent = this; editForm.Show(); // Count the number of MDI child Forms and set the title of the // main form and the newly created Form editForm.Text = "Document " + this.MdiChildren.Length.ToString(); } void OnMenuOpen(object obj, EventArgs e) { OpenDocument(); } void OpenDocument() { OpenFileDialog openDlg = new OpenFileDialog(); openDlg.Filter = "Text Files|*.txt;*.text;*.doc|All Files|*.*"; openDlg.InitialDirectory="C:"; DialogResult dr = openDlg.ShowDialog(); if(dr == DialogResult.OK) { // User click on Open // Open the file and get its content string txtFromFile = OpenFileAndReturnText(openDlg.FileName); // Instantiate our custom form and show it EditorForm editForm = new EditorForm(); editForm.MdiParent = this; // Set the title of the Form editForm.Text = openDlg.FileName; // Set the contents of the Editor Form editForm.EditText = txtFromFile; editForm.Show(); } } string OpenFileAndReturnText(string filename) { // Open the file given by param filname, read it // and return content System.IO.StreamReader reader; try { reader = new System.IO.StreamReader(filename); return reader.ReadToEnd(); } catch { MessageBox.Show("File could not be accessed"); return ""; } } void OnMenuSave(object obj, EventArgs e) { SaveActiveDocument(); } protected void SaveActiveDocument() { // Get the active MDI child Form and cast it to the custom Form EditorForm activeForm = (EditorForm) this.ActiveMdiChild; if(activeForm != null) { // Instantiate the object SaveFileDialog saveDlg = new SaveFileDialog(); // Set the suggested name saveDlg.FileName = activeForm.Text; saveDlg.InitialDirectory="C:"; // Set filter, this also sets extension saveDlg.Filter = "Text Files|*.txt; *.text; *.doc|All Files|*.*"; // Let the dialog set extension saveDlg.AddExtension = true; if(saveDlg.ShowDialog() == DialogResult.OK) { FileInfo fi = new FileInfo(saveDlg.FileName); StreamWriter sw = fi.CreateText(); sw.Write(((EditorForm)this.ActiveMdiChild).EditText); sw.Close(); } } } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { // Create an instance of the form that is to shown modally. Form modalForm = new Form(); // Create two buttons to use as the Yes and No buttons. Button yesButton = new Button (); Button noButton = new Button (); // Set the text of yes button. yesButton.Text = "Yes"; // Set the position of the button on the form. yesButton.Location = new System.Drawing.Point (10, 10); // Set the text of no button. noButton.Text = "No"; // Set the position of the button based on the location of the yes button. noButton.Location = new System.Drawing.Point (yesButton.Right + 10, yesButton.Top); // Set the caption bar text of the modal form. modalForm.Text = "Are you sure you want to close??"; // set the size modalForm.Size = new System.Drawing.Size(300,100); // Add DialogResult values of the button yesButton.DialogResult = DialogResult.Yes; noButton.DialogResult = DialogResult.No; // Add the buttons to the form. modalForm.Controls.Add(yesButton); modalForm.Controls.Add(noButton); // Display the form as a modal dialog box. if(modalForm.ShowDialog()== DialogResult.No) { // setting the Cancel property of the CancelEventArgs cancels // the event and keeps the Form open e.Cancel = true; } else { // the Yes button was clicked so we need to do nothing } // Call the base method so that the event do get raised base.OnClosing(e); } static void HandleClosing(object sender, System.ComponentModel.CancelEventArgs e) { // Create an instance of the form that is to shown modally. Form modalForm = new Form(); // Create two buttons to use as the Yes and No buttons. Button yesButton = new Button (); Button noButton = new Button (); // Set the text of yes button. yesButton.Text = "Yes"; // Set the position of the button on the form. yesButton.Location = new System.Drawing.Point (10, 10); // Set the text of no button. noButton.Text = "No"; // Set the position of the button based on the location of the yes button. noButton.Location = new System.Drawing.Point (yesButton.Right + 10, yesButton.Top); // Set the caption bar text of the modal form. modalForm.Text = "Are you sure you want to close?"; // set the size modalForm.Size = new System.Drawing.Size(300,100); // Add DialogResult values of the button yesButton.DialogResult = DialogResult.Yes; noButton.DialogResult = DialogResult.No; // Add the buttons to the form. modalForm.Controls.Add(yesButton); modalForm.Controls.Add(noButton); // Display the form as a modal dialog box. if(modalForm.ShowDialog()== DialogResult.No) { // setting the Cancel property of the CancelEventArgs cancels // the event and keeps the Form open e.Cancel = true; } else { // the Yes button was clicked so we need to do nothing // the Form will close itself. } } static void Main() { //Instantiate the derived Form MyForm myForm = new MyForm(); // Start the app Application.Run(myForm); } } } Chapter2App.zip( 38 k)[/csharp]

RichTextBox Zooming

image_pdfimage_print

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;

public class Form1 : System.Windows.Forms.Form {
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
public Form1() {
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();

this.richTextBox1.Location = new System.Drawing.Point(8, 8);
this.richTextBox1.Name = “richTextBox1”;
this.richTextBox1.Size = new System.Drawing.Size(272, 232);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = “”;
this.richTextBox1.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox1_LinkClicked);

this.button1.Location = new System.Drawing.Point(24, 256);
this.button1.Text = “Zoom Out”;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
this.button2.Location = new System.Drawing.Point(192, 256);
this.button2.Text = “Zoom In”;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
this.button3.Location = new System.Drawing.Point(112, 296);
this.button3.Text = “Normal”;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 333);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button3,
this.button2,
this.button1,
this.richTextBox1});
this.Text = “RichTextBox Zooming”;
this.ResumeLayout(false);
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e) {
float zoom = richTextBox1.ZoomFactor;
if (zoom / 2 > 0.015625)
richTextBox1.ZoomFactor = zoom / 2;
}

private void button2_Click(object sender, System.EventArgs e) {
float zoom = richTextBox1.ZoomFactor;
if (zoom * 2 < 64) richTextBox1.ZoomFactor = zoom * 2; } private void button3_Click(object sender, System.EventArgs e) { richTextBox1.ZoomFactor = 1f; } private void richTextBox1_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e) { Process p = new Process(); p.StartInfo.FileName = "C:Program FilesInternet ExplorerIEXPLORE.EXE"; p.StartInfo.Arguments = e.LinkText; p.Start(); } } [/csharp]

Scrollable Panel

image_pdfimage_print


   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace UnsualScrolling
{
    /// <summary>
    /// Summary description for ScrollablePanel.
    /// </summary>
    public class ScrollablePanel : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.Panel Panel1;
        internal System.Windows.Forms.Button Button6;
        internal System.Windows.Forms.Button Button5;
        internal System.Windows.Forms.Button Button4;
        internal System.Windows.Forms.Button Button3;
        internal System.Windows.Forms.Button Button2;
        internal System.Windows.Forms.Button Button1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public ScrollablePanel()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Panel1 = new System.Windows.Forms.Panel();
            this.Button6 = new System.Windows.Forms.Button();
            this.Button5 = new System.Windows.Forms.Button();
            this.Button4 = new System.Windows.Forms.Button();
            this.Button3 = new System.Windows.Forms.Button();
            this.Button2 = new System.Windows.Forms.Button();
            this.Button1 = new System.Windows.Forms.Button();
            this.Panel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // Panel1
            // 
            this.Panel1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.Panel1.AutoScroll = true;
            this.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.Panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                 this.Button6,
                                                                                 this.Button5,
                                                                                 this.Button4,
                                                                                 this.Button3,
                                                                                 this.Button2,
                                                                                 this.Button1});
            this.Panel1.Location = new System.Drawing.Point(4, 8);
            this.Panel1.Name = "Panel1";
            this.Panel1.Size = new System.Drawing.Size(348, 172);
            this.Panel1.TabIndex = 2;
            // 
            // Button6
            // 
            this.Button6.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button6.Location = new System.Drawing.Point(16, 180);
            this.Button6.Name = "Button6";
            this.Button6.Size = new System.Drawing.Size(168, 24);
            this.Button6.TabIndex = 5;
            this.Button6.Text = "Button6";
            // 
            // Button5
            // 
            this.Button5.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button5.Location = new System.Drawing.Point(16, 148);
            this.Button5.Name = "Button5";
            this.Button5.Size = new System.Drawing.Size(168, 24);
            this.Button5.TabIndex = 4;
            this.Button5.Text = "Button5";
            // 
            // Button4
            // 
            this.Button4.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button4.Location = new System.Drawing.Point(16, 116);
            this.Button4.Name = "Button4";
            this.Button4.Size = new System.Drawing.Size(168, 24);
            this.Button4.TabIndex = 3;
            this.Button4.Text = "Button4";
            // 
            // Button3
            // 
            this.Button3.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button3.Location = new System.Drawing.Point(16, 84);
            this.Button3.Name = "Button3";
            this.Button3.Size = new System.Drawing.Size(168, 24);
            this.Button3.TabIndex = 2;
            this.Button3.Text = "Button3";
            // 
            // Button2
            // 
            this.Button2.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button2.Location = new System.Drawing.Point(16, 52);
            this.Button2.Name = "Button2";
            this.Button2.Size = new System.Drawing.Size(168, 24);
            this.Button2.TabIndex = 1;
            this.Button2.Text = "Button2";
            // 
            // Button1
            // 
            this.Button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Button1.Location = new System.Drawing.Point(16, 20);
            this.Button1.Name = "Button1";
            this.Button1.Size = new System.Drawing.Size(168, 24);
            this.Button1.TabIndex = 0;
            this.Button1.Text = "Button1";
            // 
            // ScrollablePanel
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(360, 194);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.Panel1});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Name = "ScrollablePanel";
            this.Text = "Scrollable Panel";
            this.Panel1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        static void Main() 
        {
            Application.Run(new ScrollablePanel());
        }
    }
}