Mouse event on a control


   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

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

namespace Events
{
  /// <summary>
  /// Summary description for FormEvents.
  /// </summary>
  public class FormEvents : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Button btnOK;
    private System.Windows.Forms.Button btnCancel;
    private System.Windows.Forms.TextBox textBox1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

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

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
      // Add the following line to the constructor.
      Application.Idle += new System.EventHandler(OnIdle);
    }

    private void OnIdle (object sender, EventArgs e)
    {
      btnOK.Enabled = textBox1.Text.Length > 0;
    }

    /// <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.btnOK = new System.Windows.Forms.Button();
      this.btnCancel = new System.Windows.Forms.Button();
      this.textBox1 = new System.Windows.Forms.TextBox();
      this.SuspendLayout();
      // 
      // btnOK
      // 
      this.btnOK.BackColor = System.Drawing.SystemColors.Control;
      this.btnOK.Location = new System.Drawing.Point(56, 192);
      this.btnOK.Name = "btnOK";
      this.btnOK.Size = new System.Drawing.Size(80, 24);
      this.btnOK.TabIndex = 0;
      this.btnOK.Text = "OK";
      this.btnOK.Click += new System.EventHandler(this.btnOK_OnClick);
      this.btnOK.MouseEnter += new System.EventHandler(this.OnMouseEnter);
      this.btnOK.MouseLeave += new System.EventHandler(this.OnMouseLeave);
      // 
      // btnCancel
      // 
      this.btnCancel.BackColor = System.Drawing.SystemColors.Control;
      this.btnCancel.Location = new System.Drawing.Point(160, 192);
      this.btnCancel.Name = "btnCancel";
      this.btnCancel.Size = new System.Drawing.Size(88, 24);
      this.btnCancel.TabIndex = 1;
      this.btnCancel.Text = "Cancel";
      this.btnCancel.Click += new System.EventHandler(this.btnCancel_OnClick);
      this.btnCancel.MouseEnter += new System.EventHandler(this.OnMouseEnter);
      this.btnCancel.MouseLeave += new System.EventHandler(this.OnMouseLeave);
      // 
      // textBox1
      // 
      this.textBox1.Location = new System.Drawing.Point(48, 144);
      this.textBox1.Name = "textBox1";
      this.textBox1.Size = new System.Drawing.Size(200, 20);
      this.textBox1.TabIndex = 2;
      this.textBox1.Text = "";
      // 
      // FormEvents
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 273);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.textBox1,
                                      this.btnCancel,
                                      this.btnOK});
      this.Name = "FormEvents";
      this.Text = "FormEvents";
      this.ResumeLayout(false);

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new FormEvents());
    }

    private void btnOK_OnClick(object sender, System.EventArgs e)
    {
      MessageBox.Show ("OK button clicked", "Events");
    }

    private void btnCancel_OnClick(object sender, System.EventArgs e)
    {
      MessageBox.Show ("Cancel button clicked", "Events");
    }

    private void OnMouseEnter(object sender, System.EventArgs e)
    {
            // Test whether the sender is a button
      if (sender is Button)
      {
                // Change the OK button style to Flat, but the
                // change the background color of the Cancel button
        if (sender == btnOK)
          ((Button) sender).FlatStyle = FlatStyle.Flat;
        else if (sender == btnCancel)
          ((Button) sender).BackColor = SystemColors.ControlLightLight;
        return;
      }
            // Add code here to handle MouseEnter event for other controls
    }

    private void OnMouseLeave(object sender, System.EventArgs e)
    {
            // Test whether the sender is a button
      if (sender is Button)
      {
                // Change the OK button style to Flat, but the
                // change the background color of the Cancel button
        if (sender == btnOK)
          ((Button) sender).FlatStyle = FlatStyle.Standard;
        else if (sender == btnCancel)
          ((Button) sender).BackColor = SystemColors.Control;
        return;
      }
            // Add code here to handle MouseLeave event for other controls
    }
  }
}


           
          


Creating a menu on the fly.

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

public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.MainMenu File = new System.Windows.Forms.MainMenu();
    private System.Windows.Forms.MenuItem menuItem1 = new System.Windows.Forms.MenuItem();
    private System.Windows.Forms.MenuItem menuItem2 = new System.Windows.Forms.MenuItem();
    private System.Windows.Forms.MenuItem menuItem3 = new System.Windows.Forms.MenuItem();
    private System.Windows.Forms.Button button1 = new System.Windows.Forms.Button();
    private System.Windows.Forms.Button button2 = new System.Windows.Forms.Button();
    private System.ComponentModel.Container components = null;
    private int nIndex = 0;

    public Form1() {
        this.SuspendLayout();
        this.File.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {this.menuItem1});
        this.menuItem1.Index = 0;
        this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2, this.menuItem3});
        this.menuItem1.Text = "File";
        this.menuItem2.Index = 0;
        this.menuItem2.Text = "&amp;Close";
        this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
        this.menuItem3.Index = 1;
        this.menuItem3.Text = "E&amp;xit";
        this.button1.Location = new System.Drawing.Point(40, 208);
        this.button1.Name = "button1";
        this.button1.TabIndex = 0;
        this.button1.Text = "&amp;Add";
        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.button2.Location = new System.Drawing.Point(176, 208);
        this.button2.Name = "button2";
        this.button2.TabIndex = 1;
        this.button2.Text = "&amp;Close";
        this.button2.Click += new System.EventHandler(this.button2_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button2, this.button1});
        this.Menu = this.File;
        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }

    private void button2_Click(object sender, System.EventArgs e) {
        Close();
    }

    private void menuItemHandler(object sender, System.EventArgs e) {
        MessageBox.Show(this, "Menu Handler Called");
        MenuItem mi = (MenuItem)sender;
        MessageBox.Show(this, "Menu Item: " + mi.Text);
    }

    private void button1_Click(object sender, System.EventArgs e) {
        MenuItem mi = new MenuItem("File " + (nIndex + 1), new EventHandler(menuItemHandler));
        this.menuItem1.MenuItems.Add(mi);
        nIndex++;
    }

    private void menuItem2_Click(object sender, System.EventArgs e) {
        Close();
    }
}

    


Set MenuItem ShortCut

   
 

using System;
using System.Drawing;
using System.Windows.Forms;
   
class StandardMenu: Form
{
     MenuItem miFileOpen, miFileSave;
     MenuItem miEditCut, miEditCopy, miEditPaste;
   
     bool bDocumentPresent  = true;
     bool bNonNullSelection = true;
     bool bStuffInClipboard = false;
   
     public static void Main()
     {
          Application.Run(new StandardMenu());
     }
     public StandardMenu()
     {
          Menu = new MainMenu();
   
          MenuItem mi = new MenuItem("&amp;File");
          mi.Popup += new EventHandler(MenuFileOnPopup);
          Menu.MenuItems.Add(mi);
          int index = Menu.MenuItems.Count - 1;
   
          miFileOpen = new MenuItem("&amp;Open...");
          miFileOpen.Click += new EventHandler(MenuFileOpenOnClick);
          miFileOpen.Shortcut = Shortcut.CtrlO;
          Menu.MenuItems[index].MenuItems.Add(miFileOpen);
   
          miFileSave  = new MenuItem("&amp;Save");
          miFileSave.Click += new EventHandler(MenuFileSaveOnClick);
          miFileSave.Shortcut = Shortcut.CtrlS;
          Menu.MenuItems[index].MenuItems.Add(miFileSave);
   
          mi = new MenuItem("-");
          Menu.MenuItems[index].MenuItems.Add(mi);
   
          mi = new MenuItem("E&amp;xit");
          mi.Click += new EventHandler(MenuFileExitOnClick);
          Menu.MenuItems[index].MenuItems.Add(mi);
   
          mi = new MenuItem("&amp;Edit");
          mi.Popup += new EventHandler(MenuEditOnPopup);
          Menu.MenuItems.Add(mi);
          index = Menu.MenuItems.Count - 1;
   
          miEditCut = new MenuItem("Cu&amp;t");
          miEditCut.Click += new EventHandler(MenuEditCutOnClick);
          miEditCut.Shortcut = Shortcut.CtrlX;
          Menu.MenuItems[index].MenuItems.Add(miEditCut);
   
          miEditCopy = new MenuItem("&amp;Copy");
          miEditCopy.Click += new EventHandler(MenuEditCopyOnClick);
          miEditCopy.Shortcut = Shortcut.CtrlC;
          Menu.MenuItems[index].MenuItems.Add(miEditCopy);
   
          miEditPaste = new MenuItem("&amp;Paste");
          miEditPaste.Click += new EventHandler(MenuEditCopyOnClick);
          miEditPaste.Shortcut = Shortcut.CtrlV;
          Menu.MenuItems[index].MenuItems.Add(miEditPaste);
   
          mi = new MenuItem("&amp;Help");
          Menu.MenuItems.Add(mi);
          index = Menu.MenuItems.Count - 1;
   
          mi = new MenuItem("&amp;About StandardMenu...");
          mi.Click += new EventHandler(MenuHelpAboutOnClick);
          Menu.MenuItems[index].MenuItems.Add(mi);
     }
     void MenuFileOnPopup(object obj, EventArgs ea)
     {
          miFileSave.Enabled = bDocumentPresent;
     }
     void MenuEditOnPopup(object obj, EventArgs ea)
     {
          miEditCut.Enabled = bNonNullSelection;
          miEditCopy.Enabled = bNonNullSelection;
          miEditPaste.Enabled = bStuffInClipboard;
     }
     void MenuFileOpenOnClick(object obj, EventArgs ea)
     { 
          MessageBox.Show("File Open dialog box!", Text);
     }
     void MenuFileSaveOnClick(object obj, EventArgs ea)
     {
          MessageBox.Show("File Save dialog box!", Text);
     }
     void MenuFileExitOnClick(object obj, EventArgs ea)
     {
          Close();
     }
     void MenuEditCutOnClick(object obj, EventArgs ea)
     {
     }
     void MenuEditCopyOnClick(object obj, EventArgs ea)
     {
     }
     void MenuEditPasteOnClick(object obj, EventArgs ea)
     {
     }
     void MenuHelpAboutOnClick(object obj, EventArgs ea)
     {
          MessageBox.Show("StandardMenu ?", Text);
     }
}         

    


Font Menu

using System;
using System.Drawing;
using System.Windows.Forms;

class FontMenu: Form
{
const int iPointSize = 24;
string strFacename;

public static void Main()
{
Application.Run(new FontMenu());
}
public FontMenu()
{
strFacename = Font.Name;

Menu = new MainMenu();

MenuItem mi = new MenuItem(“&Facename”);
mi.Popup += new EventHandler(MenuFacenameOnPopup);
mi.MenuItems.Add(” “); // Necessary for pop-up call
Menu.MenuItems.Add(mi);
}
void MenuFacenameOnPopup(object obj, EventArgs ea)
{
MenuItem miFacename = (MenuItem)obj;
FontFamily[] aff = FontFamily.Families;
EventHandler ehClick = new EventHandler(MenuFacenameOnClick);
MenuItem[] ami = new MenuItem[aff.Length];

for (int i = 0; i < aff.Length; i++) { ami[i] = new MenuItem(aff[i].Name); ami[i].Click += ehClick; if (aff[i].Name == strFacename) ami[i].Checked = true; } miFacename.MenuItems.Clear(); miFacename.MenuItems.AddRange(ami); } void MenuFacenameOnClick(object obj, EventArgs ea) { MenuItem mi = (MenuItem)obj; strFacename = mi.Text; Invalidate(); } protected override void OnPaint(PaintEventArgs pea) { Graphics grfx = pea.Graphics; Font font = new Font(strFacename, iPointSize); StringFormat strfmt = new StringFormat(); grfx.DrawString("Sample Text", font, new SolidBrush(ForeColor), ClientRectangle, strfmt); } } [/csharp]

Subclass MenuItem

   
 

using System;
using System.Drawing;
using System.Windows.Forms;
   
class BetterContextMenu: Form
{
     MenuItemColor micColor;
   
     public static void Main()
     {
          Application.Run(new BetterContextMenu());
     }
     public BetterContextMenu()
     {
          Text = "Better Context Menu Demo";
   
          EventHandler eh = new EventHandler(MenuColorOnClick);
   
          MenuItemColor[] amic = 
          {
               new MenuItemColor(Color.Black,   "&amp;Black",   eh),
               new MenuItemColor(Color.Blue,    "B&amp;lue",    eh),
               new MenuItemColor(Color.Green,   "&amp;Green",   eh),
               new MenuItemColor(Color.Cyan,    "&amp;Cyan",    eh),
               new MenuItemColor(Color.Red,     "&amp;Red",     eh),
               new MenuItemColor(Color.Magenta, "&amp;Magenta", eh),
               new MenuItemColor(Color.Yellow,  "&amp;Yellow",  eh),
               new MenuItemColor(Color.White,   "&amp;White",   eh)
          };
   
          foreach (MenuItemColor mic in amic)
               mic.RadioCheck = true;
   
          micColor = amic[3];
          micColor.Checked = true;
          BackColor = micColor.Color;
   
          ContextMenu = new ContextMenu(amic);
     }
     void MenuColorOnClick(object obj, EventArgs ea)
     {
          micColor.Checked = false;
          micColor = (MenuItemColor) obj;
          micColor.Checked = true;
   
          BackColor = micColor.Color;
     }
}
class MenuItemColor: MenuItem
{
     Color clr;
   
     public MenuItemColor(Color clr, string str, EventHandler eh):
                                                            base(str, eh)
     {
          Color = clr;
     }
     public Color Color
     {
          get { return clr; }
          set { clr = value; }
     }
}

    


RadioCheck MenuItem

using System;
using System.Drawing;
using System.Windows.Forms;

class CheckAndRadioCheck: Form
{
MenuItem miColor, miFill;

public static void Main()
{
Application.Run(new CheckAndRadioCheck());
}
public CheckAndRadioCheck()
{
ResizeRedraw = true;

string[] astrColor = {“Black”, “Blue”, “Green”, “Cyan”,
“Red”, “Magenta”, “Yellow”, “White”};
MenuItem[] ami = new MenuItem[astrColor.Length + 2];
EventHandler ehColor = new EventHandler(MenuFormatColorOnClick);

for (int i = 0; i < astrColor.Length; i++) { ami[i] = new MenuItem(astrColor[i], ehColor); ami[i].RadioCheck = true; } miColor = ami[0]; miColor.Checked = true; ami[astrColor.Length] = new MenuItem("-"); miFill = new MenuItem("&Fill",new EventHandler(MenuFormatFillOnClick)); ami[astrColor.Length + 1] = miFill; MenuItem mi = new MenuItem("&Format", ami); Menu = new MainMenu(new MenuItem[] {mi}); } void MenuFormatColorOnClick(object obj, EventArgs ea) { miColor.Checked = false; miColor = (MenuItem)obj; miColor.Checked = true; Invalidate(); } void MenuFormatFillOnClick(object obj, EventArgs ea) { MenuItem mi = (MenuItem)obj; mi.Checked ^= true; Invalidate(); } protected override void OnPaint(PaintEventArgs pea) { if (miFill.Checked) { Console.WriteLine("fill"); } else { Console.WriteLine("not fill"); } } } [/csharp]

Hatch Brush Menu

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class HatchBrushMenu: Form
{
HatchStyleMenuItem hsmiChecked;
const int iMin = 0, iMax = 52;
public static void Main()
{
Application.Run(new HatchBrushMenu());
}
public HatchBrushMenu()
{
ResizeRedraw = true;

Menu = new MainMenu();
Menu.MenuItems.Add(“&Hatch-Style”);

for (HatchStyle hs = (HatchStyle)iMin; hs <= (HatchStyle)iMax;hs++) { HatchStyleMenuItem hsmi = new HatchStyleMenuItem(); hsmi.HatchStyle = hs; hsmi.Click += new EventHandler(MenuHatchStyleOnClick); if ((int)hs % 8 == 0) hsmi.BarBreak = true; Menu.MenuItems[0].MenuItems.Add(hsmi); } hsmiChecked = (HatchStyleMenuItem) Menu.MenuItems[0].MenuItems[0]; hsmiChecked.Checked = true; } void MenuHatchStyleOnClick(object obj, EventArgs ea) { hsmiChecked.Checked = false; hsmiChecked = (HatchStyleMenuItem) obj; hsmiChecked.Checked = true; Invalidate(); } protected override void OnPaint(PaintEventArgs pea) { Graphics grfx = pea.Graphics; HatchBrush hbrush = new HatchBrush(hsmiChecked.HatchStyle, Color.White, Color.Black); grfx.FillEllipse(hbrush, ClientRectangle); } } class HatchStyleMenuItem: MenuItem { const int cxImage = 32, cyImage = 32, iMargin = 2; readonly int cxCheck, cyCheck; public HatchStyle HatchStyle; public HatchStyleMenuItem() { OwnerDraw = true; cxCheck = SystemInformation.MenuCheckSize.Width; cyCheck = SystemInformation.MenuCheckSize.Height; } protected override void OnMeasureItem(MeasureItemEventArgs miea) { miea.ItemWidth = 2 * cxImage + 3 * iMargin - cxCheck; miea.ItemHeight = cyImage + 2 * iMargin; } protected override void OnDrawItem(DrawItemEventArgs diea) { diea.DrawBackground(); if ((diea.State & DrawItemState.Checked) != 0) { ControlPaint.DrawMenuGlyph(diea.Graphics, diea.Bounds.Location.X + iMargin, diea.Bounds.Location.Y + iMargin, cxImage, cyImage, MenuGlyph.Checkmark); } HatchBrush hbrush = new HatchBrush(HatchStyle, Color.White, Color.Black); diea.Graphics.FillRectangle(hbrush, diea.Bounds.X + 2 * iMargin + cxImage, diea.Bounds.Y + iMargin, cxImage, cyImage); } } [/csharp]