Csharp/CSharp Tutorial/GUI Windows Forms/Button

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

Add a Button

using System; 
using System.Windows.Forms; 
using System.Drawing; 
 
class ButtonForm : Form { 
  Button MyButton = new Button(); 
 
  public ButtonForm() { 
    Text = "Using a Button"; 
 
    MyButton = new Button(); 
    MyButton.Text = "Press Here"; 
    MyButton.Location = new Point(100, 200); 
 
    Controls.Add(MyButton); 
  }   
 
  [STAThread] 
  public static void Main() { 
    ButtonForm skel = new ButtonForm(); 
 
    Application.Run(skel); 
  } 
}

Add action handler to button

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ButtonActionForm : System.Windows.Forms.Form
{
  private System.Windows.Forms.Button button1;
  private System.ruponentModel.Container components = null;
  public ButtonActionForm()
  {
    InitializeComponent();
  }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  private void InitializeComponent()
  {
    this.button1 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    this.button1.Location = new System.Drawing.Point(109, 122);
    this.button1.Name = "button1";
    this.button1.TabIndex = 0;
    this.button1.Text = "Say Hello";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(292, 266);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                    this.button1});
    this.Name = "ButtonActionForm";
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new ButtonActionForm());
  }
  private void button1_Click(object sender, System.EventArgs e)
  {
    MessageBox.Show( this, "Hello" );
  }
}

Auto Scale Button

using System;
using System.Drawing;
using System.Windows.Forms;
class MyClass: Form
{
    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyClass());
    }
    public MyClass()
    {
        ClientSize = new Size(240, 80);
        Button btn = new Button();
        btn.Parent = this;
        btn.Text = "good!";
        btn.Size = new Size(17 * 4, 14);
        btn.Location = new Point((ClientSize.Width - btn.Width) / 2,
                                 (ClientSize.Height - btn.Height) / 2);
        AutoScaleDimensions = new Size(4, 8);
        AutoScaleMode = AutoScaleMode.Font;
    }
}

Button Background Color

using System;        
using System.Drawing;
using System.Windows.Forms;
public class ButtonBackColor : Form
{
  Button btn;
  public ButtonBackColor()
  {
        Text = "Button Properties";
    Size = new Size(300,200);
    btn = new Button();
    btn.Parent = this;
    btn.Text = "text";
    btn.Location = new Point(10,10);
    btn.BackColor = Color.LightGreen;
    
    f(btn);
  }
  static void Main() 
  {
    Application.Run(new ButtonBackColor());
  }
  private void f(Button btn)
  {
    int xSize = 100;
    int ySize = 100;
    btn.Size = new Size(xSize, ySize);
  }
}

Button Flat Style

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonFlatStyle : Form
{
  Button btn;
  int i = 1;
  FlatStyle[] flatStyles;
  Image img;
  public ButtonFlatStyle()
  {
        Text = "Button Properties";
    Size = new Size(300,200);
    img = Image.FromFile("YourFile.bmp");
    btn = new Button();
    btn.Parent = this;
    btn.Text = btn.FlatStyle.ToString();
    btn.Location = new Point(10,10);
    btn.Click += new System.EventHandler(btn_Click);
    btn.Image = img;
    ButtonSize(btn);
    FlatStyle theEnum = new FlatStyle();
    flatStyles = (FlatStyle[])Enum.GetValues(theEnum.GetType());
  }
  static void Main() 
  {
    Application.Run(new ButtonFlatStyle());
  }
  private void btn_Click(object sender, EventArgs e)
  {
    Button btn = (Button)sender;
    btn.FlatStyle = flatStyles[i];
    btn.Text = btn.FlatStyle.ToString();
    ButtonSize(btn);
    if (i < flatStyles.Length - 1)
      i++;
    else
      i = 0;
  }
  private void ButtonSize(Button btn)
  {
    int xSize = ((int)(Font.Height * .75) * btn.Text.Length) + (img.Width * 2);
    int ySize = img.Height * 2;
    btn.Size = new Size(xSize, ySize);
  }
}

Button Image

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonImage : Form
{
  Button btn;
  Image img;
  public ButtonImage()
  {
        Text = "Button Properties";
    Size = new Size(300,200);
    img = Image.FromFile("YourFile.bmp");
    btn = new Button();
    btn.Parent = this;
    btn.Text = "test";
    btn.Location = new Point(10,10);
    
      btn.Image = img;
    ButtonSize(btn);
  }
  static void Main() 
  {
    Application.Run(new ButtonImage());
  }
  private void ButtonSize(Button btn)
  {
    int xSize = 100;
    int ySize = 100;
    btn.Size = new Size(xSize, ySize);
  }
}

Button mouse event

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_MouseEnter(object sender, EventArgs e)
    {
        button1.Text = "The mouse is over me";
    }
    private void button1_MouseLeave(object sender, EventArgs e)
    {
        button1.Text = "The mouse is not over me";
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Button clickedButton = sender as Button;
        if (clickedButton != null)
        {
            clickedButton.Text = "I was clicked";
        }
    }
}
partial class Form1
{
    private void InitializeComponent()
    {
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(86, 89);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(172, 86);
        this.button1.TabIndex = 0;
        this.button1.Text = "button1";
        this.button1.MouseLeave += new System.EventHandler(this.button1_MouseLeave);
        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.button1.MouseEnter += new System.EventHandler(this.button1_MouseEnter);
        // 
        // button2
        // 
        this.button2.Location = new System.Drawing.Point(69, 25);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(75, 23);
        this.button2.TabIndex = 1;
        this.button2.Text = "button2";
        // 
        // Form1
        // 
        this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
        this.ClientSize = new System.Drawing.Size(292, 266);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);
    }
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
}
public class ButtonMouseEvent
{
    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }
}

Button PerformClick Method

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonEvent : Form
{
  Button btn1;
  Button btn2;
  public ButtonEvent()
  {
        Size = new Size(200,100);
    btn1 = new Button();
    btn1.Parent = this;
    btn1.Text = "Button1";
    btn1.Location = new Point(10,10);
    btn1.Click += new System.EventHandler(btn1_Click);
    btn2 = new Button();
    btn2.Parent = this;
    btn2.Text = "Button2";
    btn2.Location = new Point(100,10);
    btn2.Click += new System.EventHandler(btn2_Click);
  }
  static void Main() 
  {
    Application.Run(new ButtonEvent());
  }
  private void btn1_Click(object sender, EventArgs e)
  {
    MessageBox.Show("Button1 clicked.");
    btn2.PerformClick();
  }
  private void btn2_Click(object sender, EventArgs e)
  {
    MessageBox.Show("Button2 clicked.");
  }
}

Button Style: image button, standard button

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ButtonStyle : System.Windows.Forms.Form
{
  private System.ruponentModel.Container components = null;
  private System.Windows.Forms.Button btnImage;
  private System.Windows.Forms.Button btnStandard;
  private System.Windows.Forms.Button btnPopup;
  private System.Windows.Forms.Button btnFlat;
  // Hold the current text alignment
  ContentAlignment currAlignment = ContentAlignment.MiddleCenter;
  int currEnumPos = 0;
  public ButtonStyle()
  {
    InitializeComponent();
    // Set btnStandard as default accept.
    this.AcceptButton = btnStandard;
    CenterToScreen();
  }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  #region Windows Form Designer generated code
  private void InitializeComponent()
  {
    
    this.btnStandard = new System.Windows.Forms.Button();
    this.btnFlat = new System.Windows.Forms.Button();
    this.btnImage = new System.Windows.Forms.Button();
    this.btnPopup = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // btnStandard
    // 
    this.btnStandard.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
    this.btnStandard.ForeColor = System.Drawing.SystemColors.ControlText;
    this.btnStandard.Location = new System.Drawing.Point(16, 80);
    this.btnStandard.Name = "btnStandard";
    this.btnStandard.Size = new System.Drawing.Size(312, 88);
    this.btnStandard.TabIndex = 2;
    this.btnStandard.Text = "I am a standard button";
    this.btnStandard.Click += new System.EventHandler(this.btnStandard_Click);
    // 
    // btnFlat
    // 
    this.btnFlat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
    this.btnFlat.ForeColor = System.Drawing.Color.Blue;
    this.btnFlat.Location = new System.Drawing.Point(16, 24);
    this.btnFlat.Name = "btnFlat";
    this.btnFlat.Size = new System.Drawing.Size(152, 32);
    this.btnFlat.TabIndex = 0;
    this.btnFlat.Text = "I am flat...";
    // 
    // btnImage
    // 
    this.btnImage.BackgroundImage = new Bitmap("YourFile.bmp");
    this.btnImage.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold);
    this.btnImage.ForeColor = System.Drawing.Color.Black;
    this.btnImage.Location = new System.Drawing.Point(16, 192);
    this.btnImage.Name = "btnImage";
    this.btnImage.Size = new System.Drawing.Size(312, 72);
    this.btnImage.TabIndex = 3;
    this.btnImage.Text = "Image Button";
    this.btnImage.TextAlign = System.Drawing.ContentAlignment.TopCenter;
    // 
    // btnPopup
    // 
    this.btnPopup.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
    this.btnPopup.ForeColor = System.Drawing.SystemColors.ControlText;
    this.btnPopup.Location = new System.Drawing.Point(176, 24);
    this.btnPopup.Name = "btnPopup";
    this.btnPopup.Size = new System.Drawing.Size(152, 32);
    this.btnPopup.TabIndex = 1;
    this.btnPopup.Text = "I am a Popup!";
    // 
    // ButtonStyle
    // 
    this.AcceptButton = this.btnStandard;
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(340, 269);
    this.Controls.Add(this.btnImage);
    this.Controls.Add(this.btnStandard);
    this.Controls.Add(this.btnPopup);
    this.Controls.Add(this.btnFlat);
    this.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
    this.Name = "ButtonStyle";
    this.Text = "Buttons";
    this.ResumeLayout(false);
  }
  #endregion
  
  protected void btnStandard_Click (object sender, System.EventArgs e)
  {      
    Array values = Enum.GetValues(currAlignment.GetType());
  
    currEnumPos++;
    if(currEnumPos >= values.Length)
      currEnumPos = 0;
    
    currAlignment = (ContentAlignment)ContentAlignment.Parse(currAlignment.GetType(), values.GetValue(currEnumPos).ToString());
    btnStandard.TextAlign = currAlignment;
    btnStandard.Text = currAlignment.ToString();
    btnImage.ImageAlign = currAlignment;
  }
  [STAThread]
  public static void Main(string[] args) 
  {
    Application.Run(new ButtonStyle());
  }
}

Button Text Alignment

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonTextAlign : Form
{
  Button btn;
  public ButtonTextAlign()
  {
        Text = "Button Properties";
    Size = new Size(300,200);
    btn = new Button();
    btn.Parent = this;
    btn.Text = "text";
    btn.Location = new Point(10,10);
    btn.BackColor = Color.LightGreen;

    btn.TextAlign = ContentAlignment.MiddleLeft;
    
    f(btn);
  }
  static void Main() 
  {
    Application.Run(new ButtonTextAlign());
  }
  private void f(Button btn)
  {
    int xSize = 100;
    int ySize = 100;
    btn.Size = new Size(xSize, ySize);
  }
}

Calculate Button size based on its Text

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonSize : Form
{
  Button btn;
  public ButtonSize()
  {
        Text = "Button Properties";
    Size = new Size(300,200);
    btn = new Button();
    btn.Parent = this;
    btn.Text = "text";
    btn.Location = new Point(10,10);
    f(btn);
  }
  static void Main() 
  {
    Application.Run(new ButtonSize());
  }
  private void f(Button btn)
  {
    int xSize = 100;
    int ySize = 100;
    btn.Size = new Size(xSize, ySize);
  }
}

Device Independent Button

using System;
using System.Drawing;
using System.Windows.Forms;
class MyClass: Form
{
    [STAThread]
    public static void Main()
    {
        Application.Run(new MyClass());
    }
    public MyClass()
    {
        int fontHeight = Font.Height;
        ClientSize = new Size(fontHeight * 30, fontHeight * 10);
        Button btn = new Button();
        btn.Parent = this;
        btn.Text = "Button";
        btn.Size = new Size(17 * fontHeight / 2, 7 * fontHeight / 4);
        btn.Location = new Point((ClientSize.Width - btn.Width) / 2,
                                 (ClientSize.Height - btn.Height) / 2);
    }
}

extends Button

using System;
using System.Drawing;
using System.Windows.Forms;
class MessageButtonDemo: Form
{
    [STAThread]
    public static void Main()
    {
        Application.Run(new MessageButtonDemo());
    }
    public MessageButtonDemo()
    {
        MessageButton msgbtn = new MessageButton();
        msgbtn.Parent = this;
        msgbtn.Text = "Calculate";
        msgbtn.MessageBoxText = "This button is not yet implemented!";
        msgbtn.Location = new Point(50, 50);
        msgbtn.AutoSize = true;
    }
}
class MessageButton: Button
{
    string str;
    public MessageButton()
    {
        Enabled = false;
    }
    public string MessageBoxText
    {
        set
        {
            str = value;
            Enabled = value != null && value.Length > 3;
        }
        get
        {
            return str;
        }
    }
    protected override void OnClick(EventArgs args)
    {
        MessageBox.Show(MessageBoxText, Text);
    }
}

Handle button messages

using System; 
using System.Windows.Forms; 
using System.Drawing; 
 
class ButtonEventForm : Form { 
  Button MyButton = new Button(); 
 
  public ButtonEventForm() { 
    Text = "Respond to a Button"; 
 
    MyButton = new Button(); 
    MyButton.Text = "Press Here"; 
    MyButton.Location = new Point(100, 200); 
 
    // Add button event handler to list. 
    MyButton.Click += MyButtonClick; 
 
    Controls.Add(MyButton); 
  }   
 
  [STAThread] 
  public static void Main() { 
    ButtonEventForm skel = new ButtonEventForm(); 
 
    Application.Run(skel); 
  } 
 
  // Handler for MyButton. 
  protected void MyButtonClick(object who, EventArgs e) { 
    Console.WriteLine("action.");
 
  } 
}

Relocate button after pressing button

using System; 
using System.Windows.Forms; 
using System.Drawing; 
 
class ButtonEventFormLocation : Form { 
  Button MyButton = new Button(); 
 
  public ButtonEventFormLocation() { 
    Text = "Respond to a Button"; 
 
    MyButton = new Button(); 
    MyButton.Text = "Press Here"; 
    MyButton.Location = new Point(100, 200); 
 
    // Add button event handler to list. 
    MyButton.Click += MyButtonClick; 
 
    Controls.Add(MyButton); 
  }   
 
  [STAThread] 
  public static void Main() { 
    ButtonEventFormLocation skel = new ButtonEventFormLocation(); 
 
    Application.Run(skel); 
  } 
 
  // Handler for MyButton. 
  protected void MyButtonClick(object who, EventArgs e) { 
 
    if(MyButton.Top == 200) 
      MyButton.Location = new Point(10, 10); 
    else 
      MyButton.Location = new Point(100, 200); 
  } 
}

Set Label text in a button click event

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ButtonActionSetLabelTextBox : System.Windows.Forms.Form
{
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.Button button1;
    private System.ruponentModel.Container components = null;
    public ButtonActionSetLabelTextBox()
    {
        InitializeComponent();
    }
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
            if (components != null) 
            {
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
        this.label1 = new System.Windows.Forms.Label();
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.button1 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.label1.Location = new System.Drawing.Point(32, 24);
        this.label1.Name = "label1";
        this.label1.TabIndex = 0;
        this.label1.Text = "Hello World";
        this.textBox1.Location = new System.Drawing.Point(24, 128);
        this.textBox1.Name = "textBox1";
        this.textBox1.TabIndex = 1;
        this.textBox1.Text = "";
        this.button1.Location = new System.Drawing.Point(24, 168);
        this.button1.Name = "button1";
        this.button1.TabIndex = 2;
        this.button1.Text = "Say hello";
        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 266);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {this.button1,
                                                                      this.textBox1,
                                                                      this.label1});
        this.Name = "ButtonActionSetLabelTextBox";
        this.Text = "ButtonActionSetLabelTextBox";
        this.ResumeLayout(false);
    }
    #endregion
    [STAThread]
    static void Main() 
    {
        Application.Run(new ButtonActionSetLabelTextBox());
    }
    private void button1_Click(object sender, System.EventArgs e)
    {
        label1.Text = "Hello " + textBox1.Text;
    }
}

Use delegate to add an event handler to a Button

using System;
using System.Drawing;
using System.Windows.Forms;
public class ButtonEventDelegate : System.Windows.Forms.Form
{
  private Button btn;
  public ButtonEventDelegate()
  {
        Text = "Hello World";
    btn = new Button();
    btn.Location = new Point(50,50);
    btn.Text = "Goodbye";
    btn.Click += new System.EventHandler(btn_Click);
    Controls.Add(btn);
  }
  static void Main() 
  {
    Application.Run(new ButtonEventDelegate());
  }
  private void btn_Click(object sender, EventArgs e)
  {
    Application.Exit();
  }
}