Csharp/C Sharp/GUI Windows Form/Form Event — различия между версиями

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

Текущая версия на 11:32, 26 мая 2010

Bind key action to a form window

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class KeyReader : System.Windows.Forms.Form {
    private System.Windows.Forms.Label lblPress;
    private System.Windows.Forms.Label lblDown;
    private System.Windows.Forms.Label label1;
    public KeyReader() {
       InitializeComponent();
    }
     private void InitializeComponent() {
      this.lblPress = new System.Windows.Forms.Label();
      this.lblDown = new System.Windows.Forms.Label();
      this.label1 = new System.Windows.Forms.Label();
      this.SuspendLayout();
      this.lblPress.Font = new System.Drawing.Font("Microsoft Sans Serif", 30F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.lblPress.Location = new System.Drawing.Point(8, 190);
      this.lblPress.Name = "lblPress";
      this.lblPress.Size = new System.Drawing.Size(408, 48);
      this.lblPress.TabIndex = 0;
      this.lblPress.Text = "Press:";
      this.lblPress.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      this.lblDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 30F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.lblDown.Location = new System.Drawing.Point(8, 254);
      this.lblDown.Name = "lblDown";
      this.lblDown.Size = new System.Drawing.Size(408, 48);
      this.lblDown.TabIndex = 0;
      this.lblDown.Text = "Down:";
      this.lblDown.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(424, 365);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.label1,
                                                                  this.lblDown,
                                                                  this.lblPress});
      this.KeyPreview = true;
      this.Name = "KeyReader";
      this.Text = "KeyReader";
      this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.KeyReader_KeyDown);
      this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyReader_KeyPress);
      this.ResumeLayout(false);
    }
    [STAThread]
    static void Main() {
       Application.Run(new KeyReader());
    }
    private void KeyReader_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
      lblPress.Text =  "Press: " + Convert.ToString(e.KeyChar);
    }
    private void KeyReader_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
      lblDown.Text = "Down: " + Convert.ToString(e.KeyCode);
      if (e.KeyCode == Keys.ShiftKey){
         MessageBox.Show("That is one shifty character");
      }
    } 
}


Cancel Event

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ruponentModel;
  using System.Windows.Forms;
  using System.Data;
  public class Form1 : System.Windows.Forms.Form
  {
    private Button myButton; 
    public Form1()
    {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
        
            this.Closing+=new CancelEventHandler(Form_Closing);
      myButton = new Button();
      myButton.Text = "www.nfex.ru";
      myButton.Location = new System.Drawing.Point(64, 32);
      myButton.Size = new System.Drawing.Size(150, 50);
 
      Controls.Add(myButton);
    }
        public void Form_Closing(object sender,CancelEventArgs cArgs) {
            cArgs.Cancel=true; 
        }
    static void Main() 
    {
      Application.Run(new Form1());
    }
  }


Form Focus event

 
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class FocusForm : System.Windows.Forms.Form {
    private System.Windows.Forms.TextBox txtFocusForm;
    private System.Windows.Forms.Button btFocusForm;
    public FocusForm() {
        this.txtFocusForm = new System.Windows.Forms.TextBox();
        this.btFocusForm = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.txtFocusForm.Location = new System.Drawing.Point(8, 8);
        this.txtFocusForm.Size = new System.Drawing.Size(336, 20);
        this.txtFocusForm.LostFocus += new System.EventHandler(this.txtFocusForm_LostFocus);
        this.txtFocusForm.GotFocus += new System.EventHandler(this.txtFocusForm_GotFocus);
        this.btFocusForm.Location = new System.Drawing.Point(8, 40);
        this.btFocusForm.Size = new System.Drawing.Size(336, 23);
        this.btFocusForm.Click += new System.EventHandler(this.btFocusForm_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(352, 70);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.btFocusForm,
                                      this.txtFocusForm});
        this.ResumeLayout(false);
    }
    [STAThread]
    static void Main() {
        Application.Run(new FocusForm());
    }
    protected void txtFocusForm_LostFocus(object sender, EventArgs e) {
        Console.WriteLine("Goodbye!");
    }
    protected void txtFocusForm_GotFocus(object sender, EventArgs e) {
        Console.WriteLine("Hello!");
    }
    private void btFocusForm_Click(object sender, System.EventArgs e) {
        bool canFocus = txtFocusForm.CanFocus;
        bool containsFocus = this.ContainsFocus;
        bool focused = txtFocusForm.Focused;
        Console.WriteLine("Textbox can focus: " + canFocus +
                     "\nForm children contain focus: " + containsFocus +
                     "\nTextbox has focus: " + focused);
        txtFocusForm.Focus();
    }
}


Form Key Press action

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Drawing2D;
public class Form1 : System.Windows.Forms.Form{
   public Form1() {
      InitializeComponent();
   }
   private void InitializeComponent() {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Name = "Form1";
      this.Text = "Form1";
      this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);
   }
   static void Main() {
      Application.Run(new Form1());
   }
   private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
      Console.WriteLine("Key Press");
   }
}


Form Mouse down action

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Drawing2D;
public class Form1 : System.Windows.Forms.Form{
   public Form1() {
      InitializeComponent();
   }
   private void InitializeComponent() {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Name = "Form1";
      this.Text = "Form1";
      this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
   }
   static void Main() {
      Application.Run(new Form1());
   }
   private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) {
      Console.WriteLine("Mouse down");
   }
}


Form OnMove event

 

using System;
using System.Drawing;
using System.Windows.Forms;
   
class FormSize: Form
{
     public static void Main()
     {
          Application.Run(new FormSize());
     }
     public FormSize()
     {
          Text = "Form Size";
          BackColor = Color.White;
     }
     protected override void OnMove(EventArgs ea)
     {
          Invalidate();
     }
     protected override void OnPaint(PaintEventArgs pea)
     {
          Graphics graphics = pea.Graphics;
          string   str  = "Location: "        + Location        + "\n"   +
                          "ClientRectangle: " + ClientRectangle;
   
          graphics.DrawString(str, Font, Brushes.Black, 0, 0);
    }
}


Form OnResize

 

using System;
using System.Drawing;
using System.Windows.Forms;
   
class FormSize: Form
{
     public static void Main()
     {
          Application.Run(new FormSize());
     }
     public FormSize()
     {
          BackColor = Color.White;
     }
     protected override void OnResize(EventArgs ea)
     {
          Invalidate();
     }
     protected override void OnPaint(PaintEventArgs pea)
     {
          Graphics graphics = pea.Graphics;
          string   str  = "Location: "        + Location        + "\n"   +
                          "ClientRectangle: " + ClientRectangle;
   
          graphics.DrawString(str, Font, Brushes.Black, 0, 0);
    }
}


Form Paint event

using System;
using System.Drawing;
using System.Windows.Forms;
   
class PaintEvent
{
     public static void Main()
     {
          Form form   = new Form();
          form.Text   = "Paint Event";
          form.Paint += new PaintEventHandler(MyPaintHandler);
   
          Application.Run(form);
     }
     static void MyPaintHandler(object objSender, PaintEventArgs pea)
     {
          Graphics graphics = pea.Graphics;
   
          graphics.Clear(Color.Chocolate);
     }
}


Form resize and redraw

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
        private System.Windows.Forms.CheckBox chkResizeRedraw;
      public Form1() {
            InitializeComponent();
            
      }
    private void FlawedResizing_Paint(object sender, PaintEventArgs e)
    {
            ResizeRedraw = chkResizeRedraw.Checked;
            Pen pen = new Pen(Color.Red, 1);
            e.Graphics.DrawEllipse(pen, new Rectangle(new Point(0, 0),
              this.ClientSize));
            pen.Dispose();        
            
    }
    private void chkResizeRedraw_CheckedChanged(object sender, EventArgs e)
    {
      Invalidate();
    }
    private void InitializeComponent()
    {
            this.chkResizeRedraw = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // chkResizeRedraw
            // 
            this.chkResizeRedraw.AutoSize = true;
            this.chkResizeRedraw.Location = new System.Drawing.Point(102, 104);
            this.chkResizeRedraw.Name = "chkResizeRedraw";
            this.chkResizeRedraw.Size = new System.Drawing.Size(95, 17);
            this.chkResizeRedraw.TabIndex = 0;
            this.chkResizeRedraw.Text = "ResizeRedraw";
            this.chkResizeRedraw.CheckedChanged += new System.EventHandler(this.chkResizeRedraw_CheckedChanged);
            // 
            // FlawedResizing
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.chkResizeRedraw);
            this.Name = "FlawedResizing";
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
            this.Text = "FlawedResizing";
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.FlawedResizing_Paint);
            this.ResumeLayout(false);
            this.PerformLayout();
    }
      [STAThread]
      static void Main()
      {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
      }
}


Form window closing event

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ruponentModel;
  using System.Windows.Forms;
  using System.Data;
  public class Form1 : System.Windows.Forms.Form
  {
    private Button myButton; 
    public Form1()
    {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
        
            this.Closing+=new CancelEventHandler(Form_Closing);

      myButton = new Button();
      myButton.Text = "www.nfex.ru";
      myButton.Location = new System.Drawing.Point(64, 32);
      myButton.Size = new System.Drawing.Size(150, 50);
      Controls.Add(myButton);
      CenterToScreen();
    }
        public void Form_Closing(object sender,CancelEventArgs cArgs) {
            if(sender==this){
               MessageBox.Show("Form Closing Event....");
               if(sender!=this) {
                 cArgs.Cancel=true;  
               }
            }   
        }
    static void Main() 
    {
      Application.Run(new Form1());
    }
  }


Form Window event: closing, closed, load, activated, deactivated

 
using System;
using System.Windows.Forms;
using System.ruponentModel;
public class MainWindow : Form {
    private string lifeTimeInfo;
    public MainWindow() {
        this.Closing += new CancelEventHandler(MainForm_Closing);
        this.Load += new EventHandler(MainForm_Load);
        this.Closed += new EventHandler(MainForm_Closed);
        this.Activated += new EventHandler(MainForm_Activated);
        this.Deactivate += new EventHandler(MainForm_Deactivate);
    }
    protected void MainForm_Closing(object sender, CancelEventArgs e) {
        DialogResult dr = MessageBox.Show("Do you REALLY want to close this app?",
             "Closing event!", MessageBoxButtons.YesNo);
        if (dr == DialogResult.No)
            e.Cancel = true;
        else
            e.Cancel = false;
    }
    protected void MainForm_Load(object sender, System.EventArgs e) { 
        lifeTimeInfo += "Load event\n"; 
    }
    protected void MainForm_Activated(object sender, System.EventArgs e) { 
        lifeTimeInfo += "Activate event\n"; 
    }
    protected void MainForm_Deactivate(object sender, System.EventArgs e) { 
        lifeTimeInfo += "Deactivate event\n"; 
    }
    protected void MainForm_Closed(object sender, System.EventArgs e) {
        lifeTimeInfo += "Closed event\n";
        MessageBox.Show(lifeTimeInfo);
    }
    public static void Main(string[] args) {
        Application.Run(new MainWindow());
    }
}


Form window load event

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ruponentModel;
  using System.Windows.Forms;
  using System.Data;
  public class Form1 : System.Windows.Forms.Form
  {
    private Button myButton; 
    public Form1()
    {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
        
            this.Load+=new EventHandler(Form_Load);

      myButton = new Button();
      myButton.Text = "www.nfex.ru";
      myButton.Location = new System.Drawing.Point(64, 32);
      myButton.Size = new System.Drawing.Size(150, 50);
      Controls.Add(myButton);
      CenterToScreen();
    }
        public void Form_Load(object sender,EventArgs eArgs)
        {
            MessageBox.Show("Loading Form.....");
        }
    static void Main() 
    {
      Application.Run(new Form1());
    }
  }


OnClick event

 
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
   
class PrintableForm: Form
{
     public static void Main()
     {
          Application.Run(new PrintableForm());
     }
     public PrintableForm()
     {
          ResizeRedraw = true;
     }
     protected override void OnPaint(PaintEventArgs pea)
     {
          DoPage(pea.Graphics, ForeColor,ClientSize.Width, ClientSize.Height);
     }
     protected override void OnClick(EventArgs ea)
     {
          PrintDocument prndoc = new PrintDocument();
   
          prndoc.DocumentName = Text;
          prndoc.PrintPage += new PrintPageEventHandler(PrintDocumentOnPrintPage);
          prndoc.Print();
     }
     void PrintDocumentOnPrintPage(object obj, PrintPageEventArgs ppea)
     {
          Graphics grfx  = ppea.Graphics;
          SizeF    sizef = grfx.VisibleClipBounds.Size;
   
          DoPage(grfx, Color.Black, (int)sizef.Width, (int)sizef.Height);
     }
     protected virtual void DoPage(Graphics grfx, Color clr, int cx, int cy)
     {
          Pen pen = new Pen(clr);
   
          grfx.DrawLine(pen, 0,      0, cx - 1, cy - 1);
          grfx.DrawLine(pen, cx - 1, 0, 0,      cy - 1);
     }
}


OnInputLanguageChanged

 
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class InternationalText : System.Windows.Forms.Form {
    internal System.Windows.Forms.Label lblInternationalText;
    internal System.Windows.Forms.Label lblCharCode;
    private System.Windows.Forms.TextBox textBox1;
    public InternationalText() {
        this.lblInternationalText = new System.Windows.Forms.Label();
        this.lblCharCode = new System.Windows.Forms.Label();
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.SuspendLayout();
        this.lblInternationalText.Location = new System.Drawing.Point(8, 64);
        this.lblInternationalText.Size = new System.Drawing.Size(288, 23);
        this.lblCharCode.Location = new System.Drawing.Point(8, 96);
        this.lblCharCode.Size = new System.Drawing.Size(88, 23);
        this.textBox1.Location = new System.Drawing.Point(8, 24);
        this.textBox1.Size = new System.Drawing.Size(288, 20);
        this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(304, 134);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.textBox1,
                                                                      this.lblCharCode,
                                                                      this.lblInternationalText});
        this.MaximizeBox = false;
        this.ResumeLayout(false);
    }
    [STAThread]
    static void Main() {
        Application.Run(new InternationalText());
    }
    protected override void OnInputLanguageChanged(InputLanguageChangedEventArgs e) {
        MessageBox.Show(e.InputLanguage.Culture.Name);
    }
    protected override void OnInputLanguageChanging(InputLanguageChangingEventArgs e) {
        MessageBox.Show(e.InputLanguage.Culture.Name);
    }
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
        lblInternationalText.Text += e.KeyChar.ToString();
        lblCharCode.Text = ((int)e.KeyChar).ToString();
    }
}


OnKeyDown event

 

using System;
using System.Drawing;
using System.Windows.Forms;
   
class ExitOnX: Form
{
     public static void Main()
     {
          Application.Run(new ExitOnX());
     }
     public ExitOnX()
     {
          Text = "Exit on X";
     }
     protected override void OnKeyDown(KeyEventArgs kea)
     {
          if (kea.KeyCode == Keys.X)
               Close();
     }
}


OnMouseEnter, OnMouseHover, OnMouseLeave event

 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class EnterLeave: Form
{
     bool bInside = false;
   
     public static void Main()
     {
          Application.Run(new EnterLeave());
     }
     public EnterLeave()
     {
     }
     protected override void OnMouseEnter(EventArgs ea)
     {
          bInside = true;
          Invalidate();
     }
     protected override void OnMouseLeave(EventArgs ea)
     {
          bInside = false;
          Invalidate();
     }
     protected override void OnMouseHover(EventArgs ea)
     {
          Graphics grfx = CreateGraphics();
    
          grfx.Clear(Color.Red);
          System.Threading.Thread.Sleep(500);
          grfx.Clear(Color.Green);
          grfx.Dispose();
     }
     protected override void OnPaint(PaintEventArgs pea)
     {
          Graphics grfx = pea.Graphics;
   
          grfx.Clear(bInside ? Color.Green : BackColor);
     }
}


On Mouse Wheel

 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class PoePoem: Form
{
     public static void Main()
     {
          if (!SystemInformation.MouseWheelPresent)
          {
               Console.WriteLine("Program needs a mouse with a mouse wheel!");
               return;
          }
          Application.Run(new PoePoem());
     }
     public PoePoem()
     {
     }
     protected override void OnMouseWheel(MouseEventArgs mea)
     {
          Console.WriteLine(mea.Delta);
   
     }
}


Scrolling (AutoScrollMinSize)

 

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class Form1 : System.Windows.Forms.Form {
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
    protected override void OnPaint(PaintEventArgs e) {
        Graphics g;
        g = Graphics.FromHwnd(this.Handle);
        GraphicsUnit units = GraphicsUnit.Pixel;
        string path = "your.jpg";
        Image im = Image.FromFile(path);
        this.AutoScrollMinSize = new Size(im.Width, im.Height);
        //this.AutoScroll = true;
        Point P = this.AutoScrollPosition;
        Rectangle dstR = this.ClientRectangle;
        RectangleF srcR = new RectangleF(-P.X, -P.Y, dstR.Width, dstR.Height);
        g.DrawImage(im, dstR, srcR, units);
        g.Dispose();
    }
}


Scroll Shapes

 
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
public class Form1 : Form {
    private Point rectangleTopLeft = new Point(0, 0);
    private Size rectangleSize = new Size(200, 200);
    private Point ellipseTopLeft = new Point(50, 200);
    private Size ellipseSize = new Size(200, 150);
    private Pen bluePen = new Pen(Color.Blue, 3);
    private Pen redPen = new Pen(Color.Red, 2);
    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);
        Graphics dc = e.Graphics;
        Size scrollOffset = new Size(this.AutoScrollPosition);
        if (e.ClipRectangle.Top + scrollOffset.Width < 350 ||
            e.ClipRectangle.Left + scrollOffset.Height < 250) {
            Rectangle rectangleArea = new Rectangle
                (rectangleTopLeft + scrollOffset, rectangleSize);
            Rectangle ellipseArea = new Rectangle
                (ellipseTopLeft + scrollOffset, ellipseSize);
            dc.DrawRectangle(bluePen, rectangleArea);
            dc.DrawEllipse(redPen, ellipseArea);
        }
    }
    public Form1() {
        this.BackColor = Color.White;
        this.Size = new System.Drawing.Size(300, 300);
        this.AutoScrollMinSize = new Size(250, 350);
    }
    public static void Main() {
        Application.Run(new Form1());
    }
}


Uncloseable event

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ruponentModel;
  using System.Windows.Forms;
  using System.Data;
  public class Form1 : System.Windows.Forms.Form
  {
    private Button myButton; 
    public Form1()
    {
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
        
            this.Closing+=new CancelEventHandler(Form_Closing);
      myButton = new Button();
      myButton.Text = "www.nfex.ru";
      myButton.Location = new System.Drawing.Point(64, 32);
      myButton.Size = new System.Drawing.Size(150, 50);
 
      Controls.Add(myButton);
    }
        public void Form_Closing(object sender,CancelEventArgs cArgs) {
            cArgs.Cancel=true; 
        }
    static void Main() 
    {
      Application.Run(new Form1());
    }
  }