Csharp/CSharp Tutorial/GUI Windows Forms/Form

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Add a Main Menu

using System; 
using System.Windows.Forms; 
 
class AddMenuForm : Form { 
  MainMenu MyMenu; 
 
  public AddMenuForm() { 
    Text = "Adding a Main Menu"; 
    MyMenu  = new MainMenu(); 
 
    MenuItem m1 = new MenuItem("File"); 
    MyMenu.MenuItems.Add(m1); 
 
    MenuItem m2 = new MenuItem("Tools"); 
    MyMenu.MenuItems.Add(m2); 
 
    MenuItem subm1 = new MenuItem("Open"); 
    m1.MenuItems.Add(subm1); 
 
    MenuItem subm2 = new MenuItem("Close"); 
    m1.MenuItems.Add(subm2); 
 
    MenuItem subm3 = new MenuItem("Exit"); 
    m1.MenuItems.Add(subm3); 
 
    MenuItem subm4 = new MenuItem("Coordinates"); 
    m2.MenuItems.Add(subm4); 
 
    MenuItem subm5 = new MenuItem("Change Size"); 
    m2.MenuItems.Add(subm5); 
 
    MenuItem subm6 = new MenuItem("Restore"); 
    m2.MenuItems.Add(subm6); 
 
 
    subm1.Click += MMOpenClick; 
    subm2.Click += MMCloseClick; 
    subm3.Click += MMExitClick; 
    subm4.Click += MMCoordClick; 
    subm5.Click += MMChangeClick; 
    subm6.Click += MMRestoreClick; 
 
    Menu = MyMenu; 
  }   
 
  [STAThread] 
  public static void Main() { 
    AddMenuForm skel = new AddMenuForm(); 
 
    Application.Run(skel); 
  } 
 
  protected void MMCoordClick(object who, EventArgs e) { 
  } 
 
  protected void MMChangeClick(object who, EventArgs e) { 
    
  } 
 
  protected void MMRestoreClick(object who, EventArgs e) { 
    
  } 
 
  protected void MMOpenClick(object who, EventArgs e) { 
 
    Console.WriteLine("MMOpenClick"); 
  } 
 
  protected void MMCloseClick(object who, EventArgs e) { 
    Console.WriteLine("MMCloseClick"); 
  } 
 
  protected void MMExitClick(object who, EventArgs e) { 
     Console.WriteLine("Exit"); 
  } 
}

Add control to Form dynamically

using System;
using System.Drawing;
using System.Windows.Forms;
   
public class MainForm : Form
{
    public static void Main()
    {
        MainForm MyForm = new MainForm();
   
        Application.Run(MyForm);
    }
   
    public MainForm()
    {
        Button MyButton = new Button();
        
        Text = "Button Test";
        MyButton.Location = new Point(25, 25);
        MyButton.Text = "Click Me";
        MyButton.Click += new EventHandler(MyButtonClicked);
        Controls.Add(MyButton);
    }
    
    public void MyButtonClicked(object sender, EventArgs Arguments)
    {
        MessageBox.Show("The button has been clicked.");
    }
}

Build Form without by hand

using System;  
using System.Drawing;
using System.Windows.Forms;
class FormHand : Form
{
  private TextBox firstNameBox = new TextBox(); 
  private Button btnShowControls = new Button();
  
  public FormHand()
  {
    firstNameBox.Text = "Text";
    firstNameBox.Size = new Size(150, 50);
    firstNameBox.Location = new Point(10, 10);
    this.Controls.Add(firstNameBox);
    btnShowControls.Text = "Click Me";
    btnShowControls.Size = new Size(90, 90);
    btnShowControls.Location = new Point(10, 70);
    btnShowControls.Click += new EventHandler(btnShowControls_Clicked);
    this.Controls.Add(btnShowControls);
    CenterToScreen();
  }
  protected void btnShowControls_Clicked(object sender, EventArgs e)
  {
    Control.ControlCollection coll = this.Controls;
    foreach(Control c in coll)
    {
      if(c != null)
        Console.WriteLine(string.Format("Index: {0}, Text: {1}\n", coll.GetChildIndex(c, false), c.Text));
    }
    MessageBox.Show("Message", "Index and Text values for each control");
  }
    public static int Main(string[] args)
    {
    Application.Run(new FormHand());
    return 0;
    }
}

Call form constructor to create a Form object

class NewForm
{
     public static void Main()
     {
          new System.Windows.Forms.Form();
     }
}

Cal Show method to display a form

using System.Windows.Forms;
   
class ShowForm
{
     public static void Main()
     {
          Form form = new Form();
   
          form.Show();
     }
}

Change Form Cursor

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class FormCursorSetting : System.Windows.Forms.Form
{
  private System.ruponentModel.Container components = null;
  public FormCursorSetting()
  {
    InitializeComponent();
    Cursor = Cursors.WaitCursor;
    this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
  }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  private void InitializeComponent()
  {
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(292, 273);
    this.Text = "Form1";
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new FormCursorSetting());
  }
  private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
    Graphics g = e.Graphics;
    g.DrawString("String...", new Font("Times New Roman", 20), new SolidBrush(Color.Black), 40, 10);
  }
}

Change Form size in menu action

using System; 
using System.Windows.Forms; 
 
class FormChangeSize : Form { 
  MainMenu MyMenu; 
 
  public FormChangeSize() { 
    Text = "Adding a Main Menu"; 
    MyMenu  = new MainMenu(); 
 
    MenuItem m1 = new MenuItem("File"); 
    MyMenu.MenuItems.Add(m1); 
 
    MenuItem m2 = new MenuItem("Tools"); 
    MyMenu.MenuItems.Add(m2); 
 
    MenuItem subm1 = new MenuItem("Open"); 
    m1.MenuItems.Add(subm1); 
 
    MenuItem subm2 = new MenuItem("Close"); 
    m1.MenuItems.Add(subm2); 
 
    MenuItem subm3 = new MenuItem("Exit"); 
    m1.MenuItems.Add(subm3); 
 
    MenuItem subm4 = new MenuItem("Coordinates"); 
    m2.MenuItems.Add(subm4); 
 
    MenuItem subm5 = new MenuItem("Change Size"); 
    m2.MenuItems.Add(subm5); 
 
    MenuItem subm6 = new MenuItem("Restore"); 
    m2.MenuItems.Add(subm6); 
 
 
    subm4.Click += MMCoordClick; 
    subm5.Click += MMChangeClick; 
    subm6.Click += MMRestoreClick; 
 
    Menu = MyMenu; 
  }   
 
  [STAThread] 
  public static void Main() { 
    FormChangeSize skel = new FormChangeSize(); 
 
    Application.Run(skel); 
  } 
 
  protected void MMCoordClick(object who, EventArgs e) { 
    Console.WriteLine("Top:"+Top); 
    Console.WriteLine("Left:"+Left); 
    Console.WriteLine("Bottom:"+Bottom); 
    Console.WriteLine("Right:"+Right); 
    
  } 
 
  protected void MMChangeClick(object who, EventArgs e) { 
    Width = Height = 200; 
  } 
 
  protected void MMRestoreClick(object who, EventArgs e) { 
    Width = Height = 300; 
  } 
 
}

Form Dispose

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class FormDispose : System.Windows.Forms.Form
{
  private System.ruponentModel.Container components = null;
  public FormDispose()
  {
    InitializeComponent();
  }
  protected override void Dispose( bool disposing )
  {
    MessageBox.Show("Disposing this Form");
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );    
  }
  private void InitializeComponent()
  {
    this.ruponents = new System.ruponentModel.Container();
    this.Size = new System.Drawing.Size(300,300);
    this.Text = "Form1";
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new FormDispose());
  }
}

Form message filter

using System;
using System.Windows.Forms;
public class mainForm : System.Windows.Forms.Form
{
  private MyMessageFilter msgFliter = new MyMessageFilter();
  public mainForm()
  {
    Application.ApplicationExit += new EventHandler(Form_OnExit);
    Application.AddMessageFilter(msgFliter);    
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new mainForm());
  }
  private void Form_OnExit(object sender, EventArgs evArgs) 
  {
    Application.RemoveMessageFilter(msgFliter);
  }
}
public class MyMessageFilter : IMessageFilter 
{
  public bool PreFilterMessage(ref Message m) 
  {
    // Intercept the left mouse button down message.
    if (m.Msg == 513) 
    {
      Console.WriteLine("WM_LBUTTONDOWN is: " + m.Msg);
      return true;
    }
    return false;
  }
}

Inherited Form

using System;
using System.Drawing;
using System.Windows.Forms;
public class BaseForm : System.Windows.Forms.Form
{
  private Button btnClose;
  private Button btnApp;
  protected Label lbl;
  public BaseForm()
  {
    btnClose = new Button();
    btnClose.Location = new Point(25,100);
    btnClose.Size = new Size(100,25);
    btnClose.Text = "&Close";
    btnClose.Click += new System.EventHandler(btnClose_Click);
    btnApp = new Button();
    btnApp.Location = new Point(200,100);
    btnApp.Size = new Size(150,25);
    btnApp.Text = "&Base Application";
    btnApp.Click += new System.EventHandler(btnApp_Click);
    lbl = new Label();
    lbl.Location = new Point(25,25);
    lbl.Size = new Size(100,25);
    lbl.Text = "This label on BaseForm";
    Controls.AddRange(new Control[]{lbl, btnClose, btnApp});
  }
  static void Main() 
  {
    Application.Run(new BaseForm());
  }
  private void btnClose_Click(object sender, EventArgs e)
  {
    Application.Exit();
  }
  private void btnApp_Click(object sender, EventArgs e)
  {
    MessageBox.Show("This is the Base application.");
    SomeMethod();
  }
  protected virtual void SomeMethod()
  {
    MessageBox.Show("This is SomeMethod called from BaseForm.");
  }
}
public class InheritedForm : BaseForm
{
  private Button btn;
  public InheritedForm()
  {
    btn = new Button();
    btn.Location = new Point(25,150);
    btn.Size = new Size(125,25);
    btn.Text = "C&lose on Inherited";
    btn.Click += new System.EventHandler(btn_Click);
    Controls.Add(btn);
    lbl.Text = "Now from InheritedForm";
    BackColor = Color.LightBlue;
  }
  static void Main() 
  {
    Application.Run(new InheritedForm());
  }
  private void btn_Click(object sender, EventArgs e)
  {
    Application.Exit();
  }
  protected override void SomeMethod()
  {
    MessageBox.Show("This is the overridden SomeMethod called " + 
                    "from InheritedForm.");
  }
}

Inherit Form With Constructor

using System;
using System.Drawing;
using System.Windows.Forms;
   
class InheritWithConstructor: Form
{
     public static void Main()
     {
          Application.Run(new InheritWithConstructor());
     }
     public InheritWithConstructor()
     {
          Text = "Inherit with Constructor";
          BackColor = Color.White;
     }
}

Irregular form

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
public class IrregularForm : Form
{
    public IrregularForm()
    {
        this.cmdClose = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.cmdClose.Location = new System.Drawing.Point(94, 231);
        this.cmdClose.Size = new System.Drawing.Size(75, 23);
        this.cmdClose.Text = "Close";
        this.cmdClose.UseVisualStyleBackColor = true;
        this.cmdClose.Click += new System.EventHandler(this.cmdClose_Click);
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(295, 270);
        this.Controls.Add(this.cmdClose);
        this.Text = "Irregular Form";
        this.Load += new System.EventHandler(this.IrregularForm_Load);
        this.ResumeLayout(false);
    }
    private void IrregularForm_Load(object sender, EventArgs e)
    {
        GraphicsPath path = new GraphicsPath();
        Point[] pointsA = new Point[]{new Point(0, 0),new Point(40, 60), new Point(this.Width - 100, 10)};
        path.AddCurve(pointsA);
        Point[] pointsB = new Point[]{
                new Point(this.Width - 40, this.Height - 60), 
                new Point(this.Width, this.Height),
                new Point(10, this.Height)
            };
        path.AddCurve(pointsB);
        path.CloseAllFigures();
        this.Region = new Region(path);
    }
    private void cmdClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    private System.Windows.Forms.Button cmdClose;
    
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new IrregularForm());
    }
    
}

Move a Form in code

using System;
using System.Drawing;
using System.Windows.Forms;
public class FormMoveDemo : Form
{
    private bool dragging;
    private Point pointClicked;
    public FormMoveDemo()
    {
        InitializeComponent();
    }
    private void lblDrag_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            dragging = true;
            pointClicked = new Point(e.X, e.Y);
        }
        else
        {
            dragging = false;
        }
    }
    private void lblDrag_MouseMove(object sender, MouseEventArgs e)
    {
        if (dragging){
            Point pointMoveTo;
            pointMoveTo = this.PointToScreen(new Point(e.X, e.Y));
            pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);
            this.Location = pointMoveTo;
        }   
    }
    private void lblDrag_MouseUp(object sender, MouseEventArgs e)
    {
        dragging = false;
    }
    private void cmdClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    [STAThread]
    public static void Main(string[] args)
    {
        Application.Run(new FormMoveDemo());
    }
    private System.Windows.Forms.Button cmdClose= new System.Windows.Forms.Button();
    private System.Windows.Forms.Label lblDrag = new System.Windows.Forms.Label();
    private System.ruponentModel.IContainer components = null;
    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // cmdClose
        // 
        this.cmdClose.Location = new System.Drawing.Point(102, 215);
        this.cmdClose.Name = "cmdClose";
        this.cmdClose.Size = new System.Drawing.Size(76, 20);
        this.cmdClose.TabIndex = 5;
        this.cmdClose.Text = "Close";
        this.cmdClose.Click += new System.EventHandler(this.cmdClose_Click);
        // 
        // lblDrag
        // 
        this.lblDrag.BackColor = System.Drawing.Color.Navy;
        this.lblDrag.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
        this.lblDrag.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.lblDrag.ForeColor = System.Drawing.Color.White;
        this.lblDrag.Location = new System.Drawing.Point(94, 167);
        this.lblDrag.Name = "lblDrag";
        this.lblDrag.Size = new System.Drawing.Size(96, 36);
        this.lblDrag.TabIndex = 4;
        this.lblDrag.Text = "Click here to move the form!";
        this.lblDrag.MouseUp += new System.Windows.Forms.MouseEventHandler(this.lblDrag_MouseUp);
        this.lblDrag.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lblDrag_MouseMove);
        this.lblDrag.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lblDrag_MouseDown);
        // 
        // FormMoveDemo
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 266);
        this.ControlBox = false;
        this.Controls.Add(this.cmdClose);
        this.Controls.Add(this.lblDrag);
        this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.ResumeLayout(false);
    }
   
}

ResumeLayout and SuspendLayout

using System;
using System.Windows.Forms;
class MainForm : Form
{
    private Label label1;
    private TextBox textBox1;
    private Button button1;
    public MainForm()
    {
         this.label1 = new Label();
         this.textBox1 = new TextBox();
         this.button1 = new Button();
         this.SuspendLayout();
         this.label1.Location = new System.Drawing.Point(16, 36);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(128, 16);
         this.label1.TabIndex = 0;
         this.label1.Text = "Please enter your name:"; 
         this.textBox1.Location = new System.Drawing.Point(152, 32);
         this.textBox1.Name = "textBox1";
         this.textBox1.TabIndex = 1;
         this.textBox1.Text = "";
         this.button1.Location = new System.Drawing.Point(109, 80);
         this.button1.Name = "button1";
         this.button1.TabIndex = 2;
         this.button1.Text = "Enter";
         this.button1.Click += new System.EventHandler(this.button1_Click);
         this.ClientSize = new System.Drawing.Size(292, 126);
         this.Controls.Add(this.button1);
         this.Controls.Add(this.textBox1);
         this.Controls.Add(this.label1);
         this.Name = "form1";
         this.Text = "Visual C#";
         this.ResumeLayout(false);
     }
     private void button1_Click(object sender, System.EventArgs e)
     {
        System.Console.WriteLine("User entered: " + textBox1.Text);
        MessageBox.Show("Welcome, " + textBox1.Text, "Visual C#");
     }
     [STAThread]
     public static void Main()
     {
        Application.EnableVisualStyles();
        Application.Run(new MainForm());
     }
}

Scroll Form

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ScrollForm : System.Windows.Forms.Form
{
  private System.Windows.Forms.Label label1;
  private System.ruponentModel.Container components = null;
  public ScrollForm()
  {
    InitializeComponent();
  }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  private void InitializeComponent()
  {
    this.label1 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F);
    this.label1.Location = new System.Drawing.Point(16, 16);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(376, 224);
    this.label1.TabIndex = 0;
    this.label1.Text = "Scrollbars of course!";
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.AutoScroll = true;
    this.AutoScrollMinSize = new System.Drawing.Size(300, 300);
    this.ClientSize = new System.Drawing.Size(319, 136);
    this.Controls.Add(this.label1);
    this.Name = "ScrollForm";
    this.Text = "ScrollForm";
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new ScrollForm());
  }
}

Set Form Visible properties

using System.Windows.Forms;
   
class RunFormBadly
{
     public static void Main()
     {
          Form form = new Form();
   
          form.Text = "Not a Good Idea...";
          form.Visible = true;
   
          Application.Run();
     }
}

Subclass Form

using System;
using System.Drawing;
using System.Windows.Forms;
   
class InheritTheForm: Form
{
     public static void Main()
     {
          InheritTheForm form = new InheritTheForm();
          form.Text = "Inherit the Form";
          form.BackColor = Color.White;
   
          Application.Run(form);
     }
}

Text as the title

using System.Threading;
using System.Windows.Forms;
   
class ShowFormAndSleep
{
     public static void Main()
     {
          Form form = new Form();
   
          form.Show();
   
          Thread.Sleep(2500);
   
          form.Text = "My First Form";
   
          Thread.Sleep(2500);
     }
}

The difference between Form.Show and Application.Run()

using System.Windows.Forms;
   
class TwoForms
{
     public static void Main()
     {
          Form form1 = new Form();
          Form form2 = new Form();
   
          form1.Text = "Form passed to Run()";
          form2.Text = "Second form";
          form2.Show();
   
          Application.Run(form1);
   
          MessageBox.Show("Application.Run() has returned control back to Main.","TwoForms");
     }
}

The Hello, WindowsForms Application

using System.Windows.Forms;
   
public class SimpleHelloWorld : Form
{
    public static void Main()
    {
        Application.Run(new SimpleHelloWorld());
    }
   
    public SimpleHelloWorld()
    {
        Text = "Hello, WindowsForms!";
    }
}

Use Inherited form in a separate Main class

using System;
using System.Drawing;
using System.Windows.Forms;
   
class SeparateMain
{
     public static void Main()
     {
          Application.Run(new AnotherHelloWorld());
     }
}
class AnotherHelloWorld: Form
{
     public AnotherHelloWorld()
     {
          Text = "Another Hello World";
          BackColor = Color.White;
     }
     protected override void OnPaint(PaintEventArgs pea)
     {
          Graphics graphics = pea.Graphics;
   
          graphics.DrawString("Hello, Windows Forms!", Font,
                          Brushes.Black, 0, 0);
     }
}