Csharp/C Sharp/GUI Windows Form/Menu — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Содержание
Add a Main Menu
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a Main Menu.
using System;
using System.Windows.Forms;
public class MenuForm : Form {
MainMenu MyMenu;
public MenuForm() {
Text = "Adding a Main Menu";
// Create a main menu object.
MyMenu = new MainMenu();
// Add top-level menu items to the menu.
MenuItem m1 = new MenuItem("File");
MyMenu.MenuItems.Add(m1);
MenuItem m2 = new MenuItem("Tools");
MyMenu.MenuItems.Add(m2);
// Create File submenu
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);
// Create Tools submenu
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);
// Add event handlers for the menu items.
subm1.Click += new EventHandler(MMOpenClick);
subm2.Click += new EventHandler(MMCloseClick);
subm3.Click += new EventHandler(MMExitClick);
subm4.Click += new EventHandler(MMCoordClick);
subm5.Click += new EventHandler(MMChangeClick);
subm6.Click += new EventHandler(MMRestoreClick);
// Assign the menu to the form.
Menu = MyMenu;
}
[STAThread]
public static void Main() {
MenuForm skel = new MenuForm();
Application.Run(skel);
}
// Handler for main menu Coordinates selection.
protected void MMCoordClick(object who, EventArgs e) {
// Create a string that contains the cooridinates.
string size =
String.Format("{0}: {1}, {2}\n{3}: {4}, {5} ",
"Top, Left", Top, Left,
"Bottom, Right", Bottom, Right);
// Display a message box.
MessageBox.Show(size, "Window Coordinates",
MessageBoxButtons.OK);
}
// Handler for main menu Change selection.
protected void MMChangeClick(object who, EventArgs e) {
Width = Height = 200;
}
// Handler for main menu Restore selection.
protected void MMRestoreClick(object who, EventArgs e) {
Width = Height = 300;
}
// Handler for main menu Open selection.
protected void MMOpenClick(object who, EventArgs e) {
MessageBox.Show("Inactive", "Inactive",
MessageBoxButtons.OK);
}
// Handler for main menu Open selection.
protected void MMCloseClick(object who, EventArgs e) {
MessageBox.Show("Inactive", "Inactive",
MessageBoxButtons.OK);
}
// Handler for main menu Exit selection.
protected void MMExitClick(object who, EventArgs e) {
DialogResult result = MessageBox.Show("Stop Program?",
"Terminate",
MessageBoxButtons.YesNo);
if(result == DialogResult.Yes) Application.Exit();
}
}
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
internal struct TheFontSize
{
public static int Huge = 30;
public static int Normal = 20;
public static int Tiny = 8;
}
public class mainForm : System.Windows.Forms.Form
{
Color currColor = Color.MistyRose;
private int currFontSize = TheFontSize.Normal;
private StatusBarPanel sbPnlPrompt = new StatusBarPanel();
private StatusBarPanel sbPnlTime = new StatusBarPanel();
private MainMenu mainMenu = new MainMenu();
private MenuItem currentCheckedItem;
private MenuItem checkedHuge;
private MenuItem checkedNormal;
private MenuItem checkedTiny;
public mainForm()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.MenuComplete += new EventHandler(StatusForm_MenuDone);
BuildMenuSystem();
BuildStatBar();
}
static void Main()
{
Application.Run(new mainForm());
}
private void FileExit_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Exit Menu item handler");
this.Close();
}
private void FileSave_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Save Menu item handler");
}
private void ColorItem_Clicked(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string color = miClicked.Text.Remove(0,1);
this.BackColor = Color.FromName(color);
currColor = this.BackColor;
}
private void PopUp_Clicked(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text;
if(item == "Huge") {
currFontSize = TheFontSize.Huge;
currentCheckedItem = checkedHuge;
}else if(item == "Normal") {
currFontSize = TheFontSize.Normal;
currentCheckedItem = checkedNormal;
}else if(item == "Tiny") {
currFontSize = TheFontSize.Tiny;
currentCheckedItem = checkedTiny;
}
currentCheckedItem.Checked = true;
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("www.nfex.ru",
new Font("Times New Roman", (float)currFontSize),
new SolidBrush(Color.Black),
this.DisplayRectangle);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
private void HelpAbout_Clicked(object sender, EventArgs e)
{
Console.WriteLine("The amazing final app...", "About...");
}
private void FileMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
if(item == "Save..."){
sbPnlPrompt.Text = "Save current settings.";
}else{
sbPnlPrompt.Text = "Terminates this app.";
}
}
private void ColorMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
sbPnlPrompt.Text = "Select " + item;
}
private void HelpAbout_Selected(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Displays app info";
}
private void StatusForm_MenuDone(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Ready";
}
private void timer1_Tick(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
string s = t.ToLongTimeString() ;
sbPnlTime.Text = s ;
}
private void BuildMenuSystem()
{
MenuItem miFile = mainMenu.MenuItems.Add("&File");
miFile.MenuItems.Add(new MenuItem("&Save...", new EventHandler(this.FileSave_Clicked), Shortcut.CtrlS));
miFile.MenuItems.Add(new MenuItem("E&xit", new EventHandler(this.FileExit_Clicked), Shortcut.CtrlX));
miFile.MenuItems[0].Select += new EventHandler(FileMenuItem_Selected);
miFile.MenuItems[1].Select += new EventHandler(FileMenuItem_Selected);
MenuItem miColor = mainMenu.MenuItems.Add("&Background Color");
miColor.MenuItems.Add("&DarkGoldenrod", new EventHandler(ColorItem_Clicked));
miColor.MenuItems.Add("&GreenYellow", new EventHandler(ColorItem_Clicked));
for(int i = 0; i < miColor.MenuItems.Count; i++){
miColor.MenuItems[i].Select += new EventHandler(ColorMenuItem_Selected);
}
MenuItem miHelp = mainMenu.MenuItems.Add("Help");
miHelp.MenuItems.Add(new MenuItem("&About", new EventHandler(this.HelpAbout_Clicked), Shortcut.CtrlA));
miHelp.MenuItems[0].Select += new EventHandler(HelpAbout_Selected);
this.Menu = mainMenu;
ContextMenu popUpMenu = new ContextMenu();
popUpMenu.MenuItems.Add("Huge", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Normal", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Tiny", new EventHandler(PopUp_Clicked));
this.ContextMenu = popUpMenu;
checkedHuge = this.ContextMenu.MenuItems[0];
checkedNormal = this.ContextMenu.MenuItems[1];
checkedTiny = this.ContextMenu.MenuItems[2];
if(currFontSize == TheFontSize.Huge)
currentCheckedItem = checkedHuge;
else if(currFontSize == TheFontSize.Normal)
currentCheckedItem = checkedNormal;
else
currentCheckedItem = checkedTiny;
currentCheckedItem.Checked = true;
}
private void BuildStatBar()
{
Timer timer1 = new Timer();
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
StatusBar statusBar = new StatusBar();
statusBar.ShowPanels = true;
statusBar.Panels.AddRange((StatusBarPanel[])new StatusBarPanel[] {sbPnlPrompt, sbPnlTime});
sbPnlPrompt.BorderStyle = StatusBarPanelBorderStyle.None;
sbPnlPrompt.AutoSize = StatusBarPanelAutoSize.Spring;
sbPnlPrompt.Width = 62;
sbPnlPrompt.Text = "Ready";
sbPnlTime.Alignment = System.Windows.Forms.HorizontalAlignment.Right;
sbPnlTime.Width = 76;
try
{
Icon i = new Icon("icon1.ico");
sbPnlPrompt.Icon = i;
} catch(Exception e) {
MessageBox.Show(e.Message);
}
this.Controls.Add(statusBar);
}
}
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
internal struct TheFontSize
{
public static int Huge = 30;
public static int Normal = 20;
public static int Tiny = 8;
}
public class mainForm : System.Windows.Forms.Form
{
Color currColor = Color.MistyRose;
private int currFontSize = TheFontSize.Normal;
private StatusBarPanel sbPnlPrompt = new StatusBarPanel();
private StatusBarPanel sbPnlTime = new StatusBarPanel();
private MainMenu mainMenu = new MainMenu();
private MenuItem currentCheckedItem;
private MenuItem checkedHuge;
private MenuItem checkedNormal;
private MenuItem checkedTiny;
public mainForm()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.MenuComplete += new EventHandler(StatusForm_MenuDone);
BuildMenuSystem();
BuildStatBar();
}
static void Main()
{
Application.Run(new mainForm());
}
private void FileExit_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Exit Menu item handler");
this.Close();
}
private void FileSave_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Save Menu item handler");
}
private void ColorItem_Clicked(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string color = miClicked.Text.Remove(0,1);
this.BackColor = Color.FromName(color);
currColor = this.BackColor;
}
private void PopUp_Clicked(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text;
if(item == "Huge") {
currFontSize = TheFontSize.Huge;
currentCheckedItem = checkedHuge;
}else if(item == "Normal") {
currFontSize = TheFontSize.Normal;
currentCheckedItem = checkedNormal;
}else if(item == "Tiny") {
currFontSize = TheFontSize.Tiny;
currentCheckedItem = checkedTiny;
}
currentCheckedItem.Checked = true;
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("www.nfex.ru",
new Font("Times New Roman", (float)currFontSize),
new SolidBrush(Color.Black),
this.DisplayRectangle);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
private void HelpAbout_Clicked(object sender, EventArgs e)
{
Console.WriteLine("The amazing final app...", "About...");
}
private void FileMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
if(item == "Save..."){
sbPnlPrompt.Text = "Save current settings.";
}else{
sbPnlPrompt.Text = "Terminates this app.";
}
}
private void ColorMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
sbPnlPrompt.Text = "Select " + item;
}
private void HelpAbout_Selected(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Displays app info";
}
private void StatusForm_MenuDone(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Ready";
}
private void timer1_Tick(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
string s = t.ToLongTimeString() ;
sbPnlTime.Text = s ;
}
private void BuildMenuSystem()
{
MenuItem miFile = mainMenu.MenuItems.Add("&File");
miFile.MenuItems.Add(new MenuItem("&Save...", new EventHandler(this.FileSave_Clicked), Shortcut.CtrlS));
miFile.MenuItems.Add(new MenuItem("E&xit", new EventHandler(this.FileExit_Clicked), Shortcut.CtrlX));
miFile.MenuItems[0].Select += new EventHandler(FileMenuItem_Selected);
miFile.MenuItems[1].Select += new EventHandler(FileMenuItem_Selected);
MenuItem miColor = mainMenu.MenuItems.Add("&Background Color");
miColor.MenuItems.Add("&DarkGoldenrod", new EventHandler(ColorItem_Clicked));
miColor.MenuItems.Add("&GreenYellow", new EventHandler(ColorItem_Clicked));
for(int i = 0; i < miColor.MenuItems.Count; i++){
miColor.MenuItems[i].Select += new EventHandler(ColorMenuItem_Selected);
}
MenuItem miHelp = mainMenu.MenuItems.Add("Help");
miHelp.MenuItems.Add(new MenuItem("&About", new EventHandler(this.HelpAbout_Clicked), Shortcut.CtrlA));
miHelp.MenuItems[0].Select += new EventHandler(HelpAbout_Selected);
this.Menu = mainMenu;
ContextMenu popUpMenu = new ContextMenu();
popUpMenu.MenuItems.Add("Huge", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Normal", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Tiny", new EventHandler(PopUp_Clicked));
this.ContextMenu = popUpMenu;
checkedHuge = this.ContextMenu.MenuItems[0];
checkedNormal = this.ContextMenu.MenuItems[1];
checkedTiny = this.ContextMenu.MenuItems[2];
if(currFontSize == TheFontSize.Huge)
currentCheckedItem = checkedHuge;
else if(currFontSize == TheFontSize.Normal)
currentCheckedItem = checkedNormal;
else
currentCheckedItem = checkedTiny;
currentCheckedItem.Checked = true;
}
private void BuildStatBar()
{
Timer timer1 = new Timer();
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
StatusBar statusBar = new StatusBar();
statusBar.ShowPanels = true;
statusBar.Panels.AddRange((StatusBarPanel[])new StatusBarPanel[] {sbPnlPrompt, sbPnlTime});
sbPnlPrompt.BorderStyle = StatusBarPanelBorderStyle.None;
sbPnlPrompt.AutoSize = StatusBarPanelAutoSize.Spring;
sbPnlPrompt.Width = 62;
sbPnlPrompt.Text = "Ready";
sbPnlTime.Alignment = System.Windows.Forms.HorizontalAlignment.Right;
sbPnlTime.Width = 76;
try
{
Icon i = new Icon("icon1.ico");
sbPnlPrompt.Icon = i;
} catch(Exception e) {
MessageBox.Show(e.Message);
}
this.Controls.Add(statusBar);
}
}
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
internal struct TheFontSize
{
public static int Huge = 30;
public static int Normal = 20;
public static int Tiny = 8;
}
public class mainForm : System.Windows.Forms.Form
{
Color currColor = Color.MistyRose;
private int currFontSize = TheFontSize.Normal;
private StatusBarPanel sbPnlPrompt = new StatusBarPanel();
private StatusBarPanel sbPnlTime = new StatusBarPanel();
private MainMenu mainMenu = new MainMenu();
private MenuItem currentCheckedItem;
private MenuItem checkedHuge;
private MenuItem checkedNormal;
private MenuItem checkedTiny;
public mainForm()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.MenuComplete += new EventHandler(StatusForm_MenuDone);
BuildMenuSystem();
BuildStatBar();
}
static void Main()
{
Application.Run(new mainForm());
}
private void FileExit_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Exit Menu item handler");
this.Close();
}
private void FileSave_Clicked(object sender, EventArgs e)
{
Console.WriteLine("File | Save Menu item handler");
}
private void ColorItem_Clicked(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string color = miClicked.Text.Remove(0,1);
this.BackColor = Color.FromName(color);
currColor = this.BackColor;
}
private void PopUp_Clicked(object sender, EventArgs e)
{
currentCheckedItem.Checked = false;
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text;
if(item == "Huge") {
currFontSize = TheFontSize.Huge;
currentCheckedItem = checkedHuge;
}else if(item == "Normal") {
currFontSize = TheFontSize.Normal;
currentCheckedItem = checkedNormal;
}else if(item == "Tiny") {
currFontSize = TheFontSize.Tiny;
currentCheckedItem = checkedTiny;
}
currentCheckedItem.Checked = true;
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("www.nfex.ru",
new Font("Times New Roman", (float)currFontSize),
new SolidBrush(Color.Black),
this.DisplayRectangle);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
private void HelpAbout_Clicked(object sender, EventArgs e)
{
Console.WriteLine("The amazing final app...", "About...");
}
private void FileMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
if(item == "Save..."){
sbPnlPrompt.Text = "Save current settings.";
}else{
sbPnlPrompt.Text = "Terminates this app.";
}
}
private void ColorMenuItem_Selected(object sender, EventArgs e)
{
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text.Remove(0,1);
sbPnlPrompt.Text = "Select " + item;
}
private void HelpAbout_Selected(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Displays app info";
}
private void StatusForm_MenuDone(object sender, EventArgs e)
{
sbPnlPrompt.Text = "Ready";
}
private void timer1_Tick(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
string s = t.ToLongTimeString() ;
sbPnlTime.Text = s ;
}
private void BuildMenuSystem()
{
MenuItem miFile = mainMenu.MenuItems.Add("&File");
miFile.MenuItems.Add(new MenuItem("&Save...", new EventHandler(this.FileSave_Clicked), Shortcut.CtrlS));
miFile.MenuItems.Add(new MenuItem("E&xit", new EventHandler(this.FileExit_Clicked), Shortcut.CtrlX));
miFile.MenuItems[0].Select += new EventHandler(FileMenuItem_Selected);
miFile.MenuItems[1].Select += new EventHandler(FileMenuItem_Selected);
MenuItem miColor = mainMenu.MenuItems.Add("&Background Color");
miColor.MenuItems.Add("&DarkGoldenrod", new EventHandler(ColorItem_Clicked));
miColor.MenuItems.Add("&GreenYellow", new EventHandler(ColorItem_Clicked));
for(int i = 0; i < miColor.MenuItems.Count; i++){
miColor.MenuItems[i].Select += new EventHandler(ColorMenuItem_Selected);
}
MenuItem miHelp = mainMenu.MenuItems.Add("Help");
miHelp.MenuItems.Add(new MenuItem("&About", new EventHandler(this.HelpAbout_Clicked), Shortcut.CtrlA));
miHelp.MenuItems[0].Select += new EventHandler(HelpAbout_Selected);
this.Menu = mainMenu;
ContextMenu popUpMenu = new ContextMenu();
popUpMenu.MenuItems.Add("Huge", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Normal", new EventHandler(PopUp_Clicked));
popUpMenu.MenuItems.Add("Tiny", new EventHandler(PopUp_Clicked));
this.ContextMenu = popUpMenu;
checkedHuge = this.ContextMenu.MenuItems[0];
checkedNormal = this.ContextMenu.MenuItems[1];
checkedTiny = this.ContextMenu.MenuItems[2];
if(currFontSize == TheFontSize.Huge)
currentCheckedItem = checkedHuge;
else if(currFontSize == TheFontSize.Normal)
currentCheckedItem = checkedNormal;
else
currentCheckedItem = checkedTiny;
currentCheckedItem.Checked = true;
}
private void BuildStatBar()
{
Timer timer1 = new Timer();
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
StatusBar statusBar = new StatusBar();
statusBar.ShowPanels = true;
statusBar.Panels.AddRange((StatusBarPanel[])new StatusBarPanel[] {sbPnlPrompt, sbPnlTime});
sbPnlPrompt.BorderStyle = StatusBarPanelBorderStyle.None;
sbPnlPrompt.AutoSize = StatusBarPanelAutoSize.Spring;
sbPnlPrompt.Width = 62;
sbPnlPrompt.Text = "Ready";
sbPnlTime.Alignment = System.Windows.Forms.HorizontalAlignment.Right;
sbPnlTime.Width = 76;
try
{
Icon i = new Icon("icon1.ico");
sbPnlPrompt.Icon = i;
} catch(Exception e) {
MessageBox.Show(e.Message);
}
this.Controls.Add(statusBar);
}
}
Dynamic Menu
/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System.Data.SqlClient;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace DynamicMenu
{
/// <summary>
/// Summary description for DynamicMenu.
/// </summary>
public class DynamicMenu : System.Windows.Forms.Form
{
internal System.Windows.Forms.MainMenu mnuMain;
internal System.Windows.Forms.MenuItem mnuFile;
internal System.Windows.Forms.MenuItem mnuNew;
internal System.Windows.Forms.MenuItem mnuOpen;
internal System.Windows.Forms.MenuItem mnuClose;
internal System.Windows.Forms.MenuItem mnuSave;
internal System.Windows.Forms.MenuItem MenuItem12;
internal System.Windows.Forms.MenuItem mnuExit;
internal System.Windows.Forms.MenuItem mnuTools;
internal System.Windows.Forms.MenuItem mnuManageHardware;
internal System.Windows.Forms.MenuItem mnuSetupUserAccounts;
internal System.Windows.Forms.MenuItem mnuChangeDisplay;
internal System.Windows.Forms.MenuItem mnuHelp;
internal System.Windows.Forms.MenuItem mnuContents;
internal System.Windows.Forms.MenuItem MenuItem13;
internal System.Windows.Forms.MenuItem mnuAbout;
internal System.Windows.Forms.Button cmdAdmin;
internal System.Windows.Forms.Button cmdUser;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public DynamicMenu()
{
//
// 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.mnuMain = new System.Windows.Forms.MainMenu();
this.mnuFile = new System.Windows.Forms.MenuItem();
this.mnuNew = new System.Windows.Forms.MenuItem();
this.mnuOpen = new System.Windows.Forms.MenuItem();
this.mnuClose = new System.Windows.Forms.MenuItem();
this.mnuSave = new System.Windows.Forms.MenuItem();
this.MenuItem12 = new System.Windows.Forms.MenuItem();
this.mnuExit = new System.Windows.Forms.MenuItem();
this.mnuTools = new System.Windows.Forms.MenuItem();
this.mnuManageHardware = new System.Windows.Forms.MenuItem();
this.mnuSetupUserAccounts = new System.Windows.Forms.MenuItem();
this.mnuChangeDisplay = new System.Windows.Forms.MenuItem();
this.mnuHelp = new System.Windows.Forms.MenuItem();
this.mnuContents = new System.Windows.Forms.MenuItem();
this.MenuItem13 = new System.Windows.Forms.MenuItem();
this.mnuAbout = new System.Windows.Forms.MenuItem();
this.cmdAdmin = new System.Windows.Forms.Button();
this.cmdUser = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// mnuMain
//
this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile,
this.mnuTools,
this.mnuHelp});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuNew,
this.mnuOpen,
this.mnuClose,
this.mnuSave,
this.MenuItem12,
this.mnuExit});
this.mnuFile.Text = "File";
//
// mnuNew
//
this.mnuNew.Index = 0;
this.mnuNew.Text = "New";
//
// mnuOpen
//
this.mnuOpen.Index = 1;
this.mnuOpen.Text = "Open";
//
// mnuClose
//
this.mnuClose.Index = 2;
this.mnuClose.Text = "Close";
//
// mnuSave
//
this.mnuSave.Index = 3;
this.mnuSave.Text = "Save";
//
// MenuItem12
//
this.MenuItem12.Index = 4;
this.MenuItem12.Text = "-";
//
// mnuExit
//
this.mnuExit.Index = 5;
this.mnuExit.Text = "Exit";
//
// mnuTools
//
this.mnuTools.Index = 1;
this.mnuTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuManageHardware,
this.mnuSetupUserAccounts,
this.mnuChangeDisplay});
this.mnuTools.Text = "Tools";
//
// mnuManageHardware
//
this.mnuManageHardware.Index = 0;
this.mnuManageHardware.Text = "Manage Hardware";
//
// mnuSetupUserAccounts
//
this.mnuSetupUserAccounts.Index = 1;
this.mnuSetupUserAccounts.Text = "Setup User Accounts";
//
// mnuChangeDisplay
//
this.mnuChangeDisplay.Index = 2;
this.mnuChangeDisplay.Text = "Change Display";
//
// mnuHelp
//
this.mnuHelp.Index = 2;
this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuContents,
this.MenuItem13,
this.mnuAbout});
this.mnuHelp.Text = "Help";
//
// mnuContents
//
this.mnuContents.Index = 0;
this.mnuContents.Text = "Contents";
//
// MenuItem13
//
this.MenuItem13.Index = 1;
this.MenuItem13.Text = "-";
//
// mnuAbout
//
this.mnuAbout.Index = 2;
this.mnuAbout.Text = "About";
//
// cmdAdmin
//
this.cmdAdmin.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cmdAdmin.Location = new System.Drawing.Point(132, 88);
this.cmdAdmin.Name = "cmdAdmin";
this.cmdAdmin.Size = new System.Drawing.Size(80, 24);
this.cmdAdmin.TabIndex = 3;
this.cmdAdmin.Text = "Admin Level";
this.cmdAdmin.Click += new System.EventHandler(this.cmdAdmin_Click);
//
// cmdUser
//
this.cmdUser.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cmdUser.Location = new System.Drawing.Point(44, 88);
this.cmdUser.Name = "cmdUser";
this.cmdUser.Size = new System.Drawing.Size(80, 24);
this.cmdUser.TabIndex = 2;
this.cmdUser.Text = "User Level";
this.cmdUser.Click += new System.EventHandler(this.cmdUser_Click);
//
// DynamicMenu
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(256, 129);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.cmdAdmin,
this.cmdUser});
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Menu = this.mnuMain;
this.Name = "DynamicMenu";
this.Text = "Dynamic Menu";
this.Load += new System.EventHandler(this.DynamicMenu_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new DynamicMenu());
}
private void DynamicMenu_Load(object sender, System.EventArgs e)
{
cmdUser_Click(null,null);
}
private void cmdUser_Click(object sender, System.EventArgs e)
{
DataTable dtPermissions;
// Get permissions for an Admin-level user.
dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.User);
// Update the menu with these permissions.
SearchMenu(this.Menu, dtPermissions);
}
private void cmdAdmin_Click(object sender, System.EventArgs e)
{
DataTable dtPermissions;
// Get permissions for an Admin-level user.
dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.Admin);
// Update the menu with these permissions.
SearchMenu(this.Menu, dtPermissions);
}
private void SearchMenu(Menu menu, DataTable dtPermissions)
{
DataRow[] rowMatch;
foreach (MenuItem mnuItem in menu.MenuItems)
{
// See if this menu item has a corresponding row.
rowMatch = dtPermissions.Select("ControlName = "" + mnuItem.Text + """);
// If it does, configure the menu item state accordingly.
if (rowMatch.GetLength(0) > 0)
{
DBPermissions.State state;
state = (DBPermissions.State)int.Parse(rowMatch[0]["State"].ToString());
switch (state)
{
case DBPermissions.State.Hidden:
mnuItem.Visible = false;
break;
case DBPermissions.State.Disabled:
mnuItem.Enabled = false;
break;
}
}
else
{
mnuItem.Visible = true;
mnuItem.Enabled = true;
}
// Search recursively through any submenus.
if (mnuItem.MenuItems.Count > 0)
{
SearchMenu(mnuItem, dtPermissions);
}
}
}
}
public class DBPermissions
{
public enum State
{
Normal = 0,
Disabled = 1,
Hidden = 2
}
public enum Level
{
Admin,
User
}
private static SqlConnection con = new SqlConnection("Data Source=localhost;"
+ "Integrated Security=SSPI;Initial Catalog=Apress;");
public static DataTable GetPermissions(Level userLevel)
{
con.Open();
// Permissions isn"t actually actually a table in our data source.
// Instead, it"s a view that combines the important information
// from all three tables using a Join query.
string selectPermissions = "SELECT * FROM Permissions ";
switch (userLevel)
{
case Level.Admin:
selectPermissions += "WHERE LevelName = "Admin"";
break;
case Level.User:
selectPermissions += "WHERE LevelName = "User"";
break;
}
SqlCommand cmd = new SqlCommand(selectPermissions, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Permissions");
con.Close();
return ds.Tables["Permissions"];
}
}
}
/*
-- Database Dump Wizard Ver 2.2.1 (libmssql version 2.3)
--
-- Host: localhost Database: [Apress]
-- ---------------------------------------------------------
-- Server version Microsoft SQL Server Version 8.0.255
-- Dumping user-defined datatypes in "[Apress]"
-- Table structure for table "Controls"
CREATE TABLE [Controls] (
[ID] int IDENTITY NOT NULL,
[ControlName] varchar(20) NOT NULL)
GO
CREATE UNIQUE CLUSTERED INDEX PK_Controls ON [Controls] (ID)
GO
-- Dumping data for table "Controls"
--
-- Enable identity insert
SET IDENTITY_INSERT [Controls] ON
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(1, "New")
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(2, "Save")
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(3, "Manage Hardware")
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(4, "Setup User Accounts")
GO
-- Disable identity insert
SET IDENTITY_INSERT [Controls] OFF
GO
-- Table structure for table "Controls_Levels"
CREATE TABLE [Controls_Levels] (
[ID] int IDENTITY NOT NULL,
[Control_ID] int NOT NULL,
[Level_ID] int NOT NULL,
[State] smallint)
GO
CREATE UNIQUE CLUSTERED INDEX PK_Control_Levels ON [Controls_Levels] (ID)
GO
-- Dumping data for table "Controls_Levels"
--
-- Enable identity insert
SET IDENTITY_INSERT [Controls_Levels] ON
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(1, 1, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(2, 2, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(3, 3, 2, 2)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(4, 4, 2, 2)
GO
-- Disable identity insert
SET IDENTITY_INSERT [Controls_Levels] OFF
GO
-- Table structure for table "Levels"
CREATE TABLE [Levels] (
[ID] int IDENTITY NOT NULL,
[LevelName] varchar(50))
GO
CREATE UNIQUE CLUSTERED INDEX PK_UserLevels ON [Levels] (ID)
GO
-- Dumping data for table "Levels"
--
-- Enable identity insert
SET IDENTITY_INSERT [Levels] ON
GO
INSERT INTO [Levels] ([ID], [LevelName])
VALUES(1, "Admin")
GO
INSERT INTO [Levels] ([ID], [LevelName])
VALUES(2, "User")
GO
-- Disable identity insert
SET IDENTITY_INSERT [Levels] OFF
GO
CREATE VIEW [Permissions]
AS
SELECT Controls.ControlName, Levels.LevelName, Controls_Levels.State
FROM Controls INNER JOIN
Controls_Levels ON Controls.ID = Controls_Levels.Control_ID INNER JOIN
Levels ON Controls_Levels.Level_ID = Levels.ID
GO
*/
Form Menu
/*
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.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace FormMenu
{
/// <summary>
/// Summary description for FormMenuDemo.
/// </summary>
public class FormMenuDemo : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem mnuFile;
private System.Windows.Forms.MenuItem mnuFileExit;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public FormMenuDemo()
{
//
// 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.mainMenu1 = new System.Windows.Forms.MainMenu();
this.mnuFile = new System.Windows.Forms.MenuItem();
this.mnuFileExit = new System.Windows.Forms.MenuItem();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFileExit});
this.mnuFile.Text = "&File";
//
// mnuFileExit
//
this.mnuFileExit.Index = 0;
this.mnuFileExit.Text = "E&xit";
this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
//
// FormMenuDemo
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Menu = this.mainMenu1;
this.Name = "FormMenuDemo";
this.Text = "FormMenuDemo";
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new FormMenuDemo());
}
private void mnuFileExit_Click(object sender, System.EventArgs e)
{
Application.Exit ();
}
}
}
Menu Text Provider Host
/*
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.ruponentModel;
using System.Windows.Forms;
namespace ExtenderProviderHost
{
/// <summary>
/// Summary description for MenuTextProviderHost.
/// </summary>
public class MenuTextProviderHost : System.Windows.Forms.Form
{
internal System.Windows.Forms.MainMenu mnuMain;
internal System.Windows.Forms.MenuItem MenuItem1;
internal System.Windows.Forms.MenuItem mnuNew;
internal System.Windows.Forms.MenuItem mnuOpen;
internal System.Windows.Forms.MenuItem mnuSave;
private MenuTextProvider menuTextProvider1;
internal System.Windows.Forms.GroupBox GroupBox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public MenuTextProviderHost()
{
//
// 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.mnuMain = new System.Windows.Forms.MainMenu();
this.MenuItem1 = new System.Windows.Forms.MenuItem();
this.mnuNew = new System.Windows.Forms.MenuItem();
this.mnuOpen = new System.Windows.Forms.MenuItem();
this.mnuSave = new System.Windows.Forms.MenuItem();
this.menuTextProvider1 = new MenuTextProvider();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.SuspendLayout();
//
// mnuMain
//
this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem1});
//
// MenuItem1
//
this.MenuItem1.Index = 0;
this.MenuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuNew,
this.mnuOpen,
this.mnuSave});
this.MenuItem1.Text = "File";
//
// mnuNew
//
this.mnuNew.Index = 0;
this.mnuNew.Text = "New";
//
// mnuOpen
//
this.mnuOpen.Index = 1;
this.mnuOpen.Text = "Open";
//
// mnuSave
//
this.mnuSave.Index = 2;
this.mnuSave.Text = "Save";
//
// menuTextProvider1
//
this.menuTextProvider1.Location = new System.Drawing.Point(0, 244);
this.menuTextProvider1.Name = "menuTextProvider1";
this.menuTextProvider1.Size = new System.Drawing.Size(292, 22);
this.menuTextProvider1.TabIndex = 0;
this.menuTextProvider1.Text = "menuTextProvider1";
//
// GroupBox1
//
this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.GroupBox1.Location = new System.Drawing.Point(0, 240);
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.Size = new System.Drawing.Size(292, 4);
this.GroupBox1.TabIndex = 2;
this.GroupBox1.TabStop = false;
this.GroupBox1.Text = "GroupBox1";
//
// MenuTextProviderHost
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.GroupBox1,
this.menuTextProvider1});
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Menu = this.mnuMain;
this.Name = "MenuTextProviderHost";
this.Text = "MenuTextProviderHost";
this.Load += new System.EventHandler(this.MenuTextProviderHost_Load);
this.ResumeLayout(false);
}
#endregion
private void MenuTextProviderHost_Load(object sender, System.EventArgs e)
{
menuTextProvider1.SetHelpText(mnuNew, " Create a new document and abandon the current one.");
}
static void Main()
{
Application.Run(new MenuTextProviderHost());
}
}
[ProvideProperty("HelpText", typeof(string))]
public class MenuTextProvider : StatusBar, IExtenderProvider
{
public bool CanExtend(object extendee)
{
if (extendee.GetType() == typeof(MenuItem))
{
return true;
}
else
{
return false;
}
}
private Hashtable helpText = new Hashtable();
public void SetHelpText(object extendee, string value)
{
// Specifying an empty value removes the extension.
if (value == "")
{
helpText.Remove(extendee);
MenuItem mnu = (MenuItem)extendee;
mnu.Select -= new EventHandler(MenuSelect);
}
else
{
helpText[extendee] = value;
MenuItem mnu = (MenuItem)extendee;
mnu.Select += new EventHandler(MenuSelect);
}
}
public string GetHelpText(object extendee)
{
if (helpText[extendee] != null)
{
return helpText[extendee].ToString();
}
else
{
return string.Empty;
}
}
private void MenuSelect(object sender, System.EventArgs e)
{
this.Text = helpText[sender].ToString();
}
}
}