动态创建菜单,menustrip,根据权限显示菜单,控制菜单可用,反射,给窗体传值,反射对象传值【转】
Posted on 2010-04-29 17:04 Happy Coding 阅读(1099) 评论(0) 编辑 收藏 举报using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Kimbanx.SecurityDiskSystem.FactoryTools.MenuItem;
using Program.BLL;
using Kimbanx.SecurityDiskSystem.FactoryTools.DBDAL;
using Program.Model;
using System.Threading;
using System.Diagnostics;
namespace Kimbanx.SecurityDiskSystem.FactoryTools
{
public partial class frmMDIMain : Form
{
private List<int> loginUserAuthIDList;
public frmMDIMain()
{
InitializeComponent();
}
private void ExitSysMenu_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void checkDisk_Click(object sender, EventArgs e)
{
CheckDiskForm checkDiskForm = new CheckDiskForm();
checkDiskForm.ShowDialog();
}
private void reInStockDisk_Click(object sender, EventArgs e)
{
ReInStockDisk reInStockDisk = new ReInStockDisk();
reInStockDisk.ShowDialog();
}
private void createConfigMenu_Click(object sender, EventArgs e)
{
CreatePolicyConfig createCfg = new CreatePolicyConfig(ConfigFormState.Create, "创建策略配置");
createCfg.ShowDialog();
}
private void ProduceDiskMenu_Click(object sender, EventArgs e)
{
ProduceDisk produceDisk = new ProduceDisk();
produceDisk.ShowDialog();
}
private void resetDisk_Click(object sender, EventArgs e)
{
ResetDiks resetDisk = new ResetDiks();
resetDisk.ShowDialog();
}
private void ResetPersonalDisk_Click(object sender, EventArgs e)
{
ResetPersonalDisk resetPersonalDisk = new ResetPersonalDisk();
resetPersonalDisk.ShowDialog();
}
private void ImportNewCfg_Click(object sender, EventArgs e)
{
ImportNewCfg importCfg = new ImportNewCfg();
importCfg.ShowDialog();
}
private void UpdateDiskTools_Click(object sender, EventArgs e)
{
UpdateDiskSoft updateDisk = new UpdateDiskSoft();
updateDisk.ShowDialog();
}
private void viewDiskInfoMenu_Click(object sender, EventArgs e)
{
ShowDiskInfo showDiskInfo = new ShowDiskInfo();
showDiskInfo.ShowDialog();
}
private void selectConfigMenu_Click(object sender, EventArgs e)
{
CreatePolicyConfig viewCfg = new CreatePolicyConfig(ConfigFormState.View, "查看策略配置");
viewCfg.ShowDialog();
}
private void importConfigMenu_Click(object sender, EventArgs e)
{
CreatePolicyConfig importCfg = new CreatePolicyConfig(ConfigFormState.Import, "迁入策略配置");
importCfg.ShowDialog();
}
private void exCfgMenu_Click(object sender, EventArgs e)
{
CreatePolicyConfig exCfg = new CreatePolicyConfig(ConfigFormState.Export, "迁出策略配置");
exCfg.ShowDialog();
}
private void exManCenterCfgMenu_Click(object sender, EventArgs e)
{
CreatePolicyConfig exManCenter = new CreatePolicyConfig(ConfigFormState.ExportManagementCenter, "导出管控中心策略配置(企业版)");
exManCenter.ShowDialog();
}
private void ManRoleMenu_Click(object sender, EventArgs e)
{
ManageRoleForm manageRoleForm = new ManageRoleForm();
manageRoleForm.ShowDialog();
}
private void ManageUserMenu_Click(object sender, EventArgs e)
{
ManSysUserForm1 manSysUserForm = new ManSysUserForm1();
manSysUserForm.ShowDialog();
}
private void SysParaMenu_Click(object sender, EventArgs e)
{
SysParaForm sysParaForm = new SysParaForm();
sysParaForm.ShowDialog();
}
private void SysLogMenu_Click(object sender, EventArgs e)
{
SelectSysLogForm1 selectSysLogForm = new SelectSysLogForm1();
selectSysLogForm.ShowDialog();
}
private void ModifyPwdMenu_Click(object sender, EventArgs e)
{
ModifyUserPwdForm1 modifyUserPasswordForm = new ModifyUserPwdForm1();
modifyUserPasswordForm.ShowDialog();
}
private void frmMDIMain_Load(object sender, EventArgs e)
{
loginUserAuthIDList = new List<int>();
BLLUserInRole bllUserInRole = new BLLUserInRole();
DataTable roleDT = bllUserInRole.GetRoleDataTableByUserID(Helper.Helper.Log.Opeid);
List<int> roleIDList = new List<int>();
foreach (DataRow row in roleDT.Rows)
{
roleIDList.Add(Convert.ToInt32(row["RoleInfoAutoID"].ToString()));
}
loginUserAuthIDList = MenuItemDAL.GetAllMenuList(roleIDList);
CreateMenu(MenuItem.MenuItem.MenuContent);
this.menuStrip1.Items.Add(new ToolStripMenuItem("重新登录", null, new EventHandler(reload_Click)));
this.menuStrip1.Items.Add(new ToolStripMenuItem("退出系统",null,new EventHandler(ExitSysMenu_Click)));
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (item.DropDownItems.Count > 0)
{
showMenu(item);
}
}
}
private void reload_Click(object sender, EventArgs e)
{
//Process process = new Process();
//process.StartInfo.FileName = "Kimbanx.SecurityDiskSystem.FactoryTools.exe";
//process.Start();
//Application.Exit();
//bool flag = false;
//Mutex mutex = new Mutex(true, "Kimbanx.SecurityDiskSystem.FactoryTools.LoginForm", out flag);
//if (flag)
//{
// LoginForm loginForm = new LoginForm();
// if (loginForm.ShowDialog() == DialogResult.OK)
// {
// Application.Run(new frmMDIMain());
// }
//}
//else
//{
// MessageBox.Show("已经存在运行的实例!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
// Application.Exit();
//}
}
private void showMenu(ToolStripMenuItem item)
{
for (int i = 0; i < item.DropDownItems.Count; i++)
{
if (((ToolStripMenuItem) item.DropDownItems[i]).DropDownItems.Count> 0)
{
showMenu((ToolStripMenuItem)item.DropDownItems[i]);
}
else
{
if (loginUserAuthIDList.Contains(Convert.ToInt32(item.DropDownItems[i].Name)))
{
item.DropDownItems[i].Enabled = true;
}
else
{ item.DropDownItems[i].Enabled = false; }
}
}
}
/**/
/// <summary>
/// 动态创建菜单
/// </summary>
private void CreateMenu(string menuContent)
{
//定义一个主菜单
MenuStrip mainMenu = new MenuStrip();
DataSet ds = new DataSet();
//从XML中读取数据。数据结构后面详细讲一下。
//StreamReader sr = new StreamReader(menuContent);
//ds.ReadXml(sr);
ds.ReadXml(Path.Combine(Application.StartupPath, "..\\..\\MenuItem\\MenuItem.xml"));
DataView dv = ds.Tables[0].DefaultView;
//通过DataView来过滤数据首先得到最顶层的菜单
dv.RowFilter = "ParentItemID=0";
for (int i = 0; i < dv.Count; i++)
{
//创建一个菜单项
ToolStripMenuItem topMenu = new ToolStripMenuItem();
//给菜单赋Text值。也就是在界面上看到的值。
topMenu.Text = dv[i]["Text"].ToString();
topMenu.Name = dv[i]["ItemID"].ToString();
//如果是有下级菜单则通过CreateSubMenu方法来创建下级菜单
if (Convert.ToInt16(dv[i]["IsModule"]) == 1)
{
//以ref的方式将顶层菜单传递参数,因为他可以在赋值后再回传。--也许还有更好的方法^_^.
CreateSubMenu(ref topMenu, Convert.ToInt32(dv[i]["ItemID"]), ds.Tables[0]);
}
//显示应用程序中已打开的 MDI 子窗体列表的菜单项
mainMenu.MdiWindowListItem = topMenu;
//将递归附加好的菜单加到菜单根项上。
mainMenu.Items.Add(topMenu);
}
ToolStripMenuItem exitMenu = new ToolStripMenuItem();
mainMenu.Dock = DockStyle.Top;
//将窗体的MainMenuStrip梆定为mainMenu.
this.menuStrip1 = mainMenu;
//这句很重要。如果不写这句菜单将不会出现在主窗体中。
this.Controls.Add(mainMenu);
}
/**/
/// <summary>
/// 创建子菜单
/// </summary>
/// <param name="topMenu">父菜单项</param>
/// <param name="ItemID">父菜单的ID</param>
/// <param name="dt">所有菜单数据集</param>
private void CreateSubMenu(ref ToolStripMenuItem topMenu, int ItemID, DataTable dt)
{
DataView dv = new DataView(dt);
//过滤出当前父菜单下在所有子菜单数据(仅为下一层的)
dv.RowFilter = "ParentItemID=" + ItemID.ToString();
for (int i = 0; i < dv.Count; i++)
{
//创建子菜单项
ToolStripMenuItem subMenu = new ToolStripMenuItem();
subMenu.Text = dv[i]["Text"].ToString();
subMenu.Name = dv[i]["ItemID"].ToString();
//如果还有子菜单则继续递归加载。
if (Convert.ToInt16(dv[i]["IsModule"]) == 1)
{
//递归调用
CreateSubMenu(ref subMenu, Convert.ToInt32(dv[i]["ItemID"]), dt);
}
else
{
//扩展属性可以加任何想要的值。这里用formName属性来加载窗体。
subMenu.Tag = dv[i]["FormName"].ToString();
//给没有子菜单的菜单项加事件。
subMenu.Click += new EventHandler(subMenu_Click);
}
//if (dv[i]["ImageName"].ToString().Length > 0)
//{
// //设置菜单项前面的图票为16X16的图片文件。
// Image img = Image.FromFile(@"..\..\Image\" + dv[i]["ImageName"].ToString());
// subMenu.Image = img;
// subMenu.Image.Tag = dv[i]["ImageName"].ToString();
//}
//将菜单加到顶层菜单下。
topMenu.DropDownItems.Add(subMenu);
}
}
/**/
/// <summary>
/// 菜单单击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void subMenu_Click(object sender, EventArgs e)
{
//tag属性在这里有用到。
string formName = ((ToolStripMenuItem)sender).Tag.ToString();
CreateFormInstance(formName, Convert.ToInt32(((ToolStripMenuItem)sender).Name));
}
/**/
/// <summary>
/// 创建form实例。
/// </summary>
/// <param name="formName">form的类名</param>
private void CreateFormInstance(string formName,int id)
{
bool flag = false;
//遍历主窗口上的所有子菜单
for (int i = 0; i < this.MdiChildren.Length; i++)
{
//如果所点的窗口被打开则重新激活
if (this.MdiChildren[i].Tag.ToString().ToLower() == formName.ToLower())
{
this.MdiChildren[i].Activate();
this.MdiChildren[i].Show();
this.MdiChildren[i].WindowState = FormWindowState.Normal;
flag = true;
break;
}
}
if (!flag)
{
//如果不存在则用反射创建form窗体实例。
Assembly asm = Assembly.Load("Kimbanx.SecurityDiskSystem.FactoryTools");//程序集名
object frmObj=null;
switch(id)
{
case 48:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName), new object[] { ConfigFormState.Create, "创建策略配置" });
break;
case 49:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName), new object[] { ConfigFormState.View, "查看策略配置" });
break;
case 50:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName), new object[] { ConfigFormState.Import, "迁入策略配置" });
break;
case 51:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName), new object[] { ConfigFormState.Export, "迁出策略配置" });
break;
case 52:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName), new object[] { ConfigFormState.ExportManagementCenter, "导出管控中心用策略配置(企业版)" });
break;
default:
frmObj = Activator.CreateInstance(Type.GetType("Kimbanx.SecurityDiskSystem.FactoryTools." + formName));
break;
}
// object frmObj = asm.CreateInstance("Kimbanx.SecurityDiskSystem.FactoryTools." + formName);//程序集+form的类名。
Form frms = (Form)frmObj;
//tag属性要重新写一次,否则在第二次的时候取不到。原因还不清楚。有知道的望告知。
frms.Tag = formName.ToString();
frms.MdiParent = this;
frms.Show();
}
}
}
}
菜单的xml文件如下所示:这个是我从别人的博客中摘抄的。
<?xml version="1.0" encoding="utf-8" ?>
<Menus>
<MenuItem>
<Text>资料管理</Text>
<ItemID>1000</ItemID>
<ParentItemID>0</ParentItemID>
<FormName></FormName>
<IsModule>1</IsModule>
<Level>1</Level>
<ImageName>01.bmp</ImageName>
</MenuItem>
<MenuItem>
<Text>产品管理</Text>
<ItemID>1100</ItemID>
<ParentItemID>0</ParentItemID>
<FormName></FormName>
<IsModule>1</IsModule>
<Level>1</Level>
<ImageName>16x16_ico_pdf.gif</ImageName>
</MenuItem>
<MenuItem>
<Text>进书管理</Text>
<ItemID>100001</ItemID>
<ParentItemID>1000</ParentItemID>
<FormName>frmInputBooks</FormName>
<IsModule>0</IsModule>
<Level>2</Level>
<ImageName>crest16x16.gif</ImageName>
</MenuItem>
<MenuItem>
<Text>买卖管理</Text>
<ItemID>100002</ItemID>
<ParentItemID>1000</ParentItemID>
<FormName></FormName>
<IsModule>1</IsModule>
<Level>2</Level>
<ImageName>ico16-16.gif</ImageName>
</MenuItem>
<MenuItem>
<Text>作业管理</Text>
<ItemID>110001</ItemID>
<ParentItemID>1100</ParentItemID>
<FormName></FormName>
<IsModule>1</IsModule>
<Level>2</Level>
<ImageName>ico_info_16x16_mask.gif</ImageName>
</MenuItem>
<MenuItem>
<Text>买书管理</Text>
<ItemID>10000201</ItemID>
<ParentItemID>100002</ParentItemID>
<FormName></FormName>
<IsModule>1</IsModule>
<Level>3</Level>
<ImageName>ico_tmn_16x16.jpg</ImageName>
</MenuItem>
<MenuItem>
<Text>买sss管理</Text>
<ItemID>1000020101</ItemID>
<ParentItemID>10000201</ParentItemID>
<FormName>frmBuyBook</FormName>
<IsModule>0</IsModule>
<Level>4</Level>
<ImageName>ico16-16.gif</ImageName>
</MenuItem>
<MenuItem>
<Text>dsafasdf</Text>
<ItemID>11000101</ItemID>
<ParentItemID>110001</ParentItemID>
<FormName>frmBuyBook</FormName>
<IsModule>0</IsModule>
<Level>3</Level>
<ImageName>ico16-16.gif</ImageName>
</MenuItem>
</Menus>
下面来说明一下XML文件。
Text:为显示在窗体上的文字,
ItemID:为菜单的ID,
ParentItemID:为此菜单的父菜单ID如果是顶级菜单则为0
FormName:为单击菜单所要显示的窗体类名如果是还有下级菜单的则不要写。
IsModule:是否还有子菜单1有,0没有
Level:菜单所在的层数。目前还没用到。
ImageName:菜单前的图标为16x16的图片文件,这个我这里没有用到
在这里还可以根据自己的需要加其它的属性,也可以写成以数据库的方式。
这是我目前用到的功能。我会继续发表我做这个小软件的心得体会。希望对大家有所帮助。