首页 > 代码库 > [WinForm]WinForm之简易权限管理

[WinForm]WinForm之简易权限管理

   [摘要]陆续在今年写了固定资产和低值易耗品,采购模具管理以及将要进行的制程管理等子系统,都是各自写一个小程序,每次都要搭建下环境。每做一个小系统部署的时候都得打包一次。干脆做一个简易框架去实现吧。

权限管理仿照自己协同工作平台。

表一:菜单管理

CREATE TABLE [dbo].[WinForm_MenuInfo](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[NAME] [nvarchar](100) NOT NULL,
	[PARENTID] [int] NOT NULL,
	[FORMNAME] [nvarchar](200) NULL,
	[TYPE] [int] NULL,
	[SORTINDEX] [int] NULL,
 CONSTRAINT [PK_WinForm_MenuInfo] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[WinForm_MenuInfo] ADD  CONSTRAINT [DF_WinForm_MenuInfo_PARENTID]  DEFAULT ((-1)) FOR [PARENTID]
GO

ALTER TABLE [dbo].[WinForm_MenuInfo] ADD  CONSTRAINT [DF_WinForm_MenuInfo_TYPE]  DEFAULT ((0)) FOR [TYPE]
GO

ALTER TABLE [dbo].[WinForm_MenuInfo] ADD  CONSTRAINT [DF_WinForm_MenuInfo_SORTINDEX]  DEFAULT ((0)) FOR [SORTINDEX]
GO

表二:角色管理

CREATE TABLE [dbo].[WinForm_RoleInfo](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[NAME] [nvarchar](100) NOT NULL,
	[DESCRIPT] [nvarchar](500) NULL,
	[PARENTID] [int] NOT NULL,
 CONSTRAINT [PK_WinForm_RoleInfo] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

表三:角色菜单

CREATE TABLE [dbo].[WinForm_RoleMenu](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[rid] [int] NOT NULL,
	[mid] [int] NOT NULL,
 CONSTRAINT [PK_WinForm_RoleMenu] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

菜单管理:


角色授权:


用户角色管理


重点来了:

WINFORM如何加载呢?

简易布局:

顶部标题

左边是树形菜单

右边是TabContorl。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERPSystem.DBUtility;

namespace ERPSystem
{
    public partial class FrmMain : Form
    {
        public int userid;
        public FrmMain(int userid)
        {
            InitializeComponent();
            this.userid = userid;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.Icon = Icon.FromHandle(new Bitmap(imageList1.Images[2]).GetHicon());
            //清空控件
            //this.MainTabControl.TabPages.Clear();
            //绘制的方式OwnerDrawFixed表示由窗体绘制大小也一样
            this.MainTabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MainTabControl.Padding = new System.Drawing.Point(CLOSE_SIZE, CLOSE_SIZE);
            this.MainTabControl.DrawItem += new DrawItemEventHandler(this.MainTabControl_DrawItem);
            this.MainTabControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MainTabControl_MouseDown);
            BindTree();
            this.trvMeun.ExpandAll();
        }
        const int CLOSE_SIZE = 10;
        //tabPage标签图片
        Bitmap image = global::ERPSystem.Properties.Resources.Close;

        //绘制“X”号即关闭按钮
        private void MainTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Rectangle myTabRect = this.MainTabControl.GetTabRect(e.Index);

                //先添加TabPage属性   
                e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, this.Font, SystemBrushes.ControlText, myTabRect.X + 2, myTabRect.Y + 2);

                //再画一个矩形框
                using (Pen p = new Pen(Color.White))
                {
                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(p, myTabRect);
                }

                //填充矩形框
                Color recColor = e.State == DrawItemState.Selected ? Color.White : Color.White;
                using (Brush b = new SolidBrush(recColor))
                {
                    e.Graphics.FillRectangle(b, myTabRect);
                }

                //画关闭符号
                using (Pen objpen = new Pen(Color.Black))
                {
                    ////=============================================
                    //自己画X
                    ////"\"线
                    //Point p1 = new Point(myTabRect.X + 3, myTabRect.Y + 3);
                    //Point p2 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + myTabRect.Height - 3);
                    //e.Graphics.DrawLine(objpen, p1, p2);
                    ////"/"线
                    //Point p3 = new Point(myTabRect.X + 3, myTabRect.Y + myTabRect.Height - 3);
                    //Point p4 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + 3);
                    //e.Graphics.DrawLine(objpen, p3, p4);

                    ////=============================================
                    //使用图片
                    Bitmap bt = new Bitmap(image);
                    Point p5 = new Point(myTabRect.X, 4);
                    e.Graphics.DrawImage(bt, p5);
                    //e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, this.Font, objpen.Brush, p5);
                }
                e.Graphics.Dispose();
            }
            catch (Exception)
            { }
        }

        //关闭按钮功能
        private void MainTabControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = e.X, y = e.Y;
                //计算关闭区域   
                Rectangle myTabRect = this.MainTabControl.GetTabRect(this.MainTabControl.SelectedIndex);

                myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                myTabRect.Width = CLOSE_SIZE;
                myTabRect.Height = CLOSE_SIZE;

                //如果鼠标在区域内就关闭选项卡   
                bool isClose = x > myTabRect.X && x < myTabRect.Right && y > myTabRect.Y && y < myTabRect.Bottom;
                if (isClose == true)
                {
                    this.MainTabControl.TabPages.Remove(this.MainTabControl.SelectedTab);
                }
            }
        }
        /// <summary>
        /// 初始化树形菜单
        /// </summary>
        private void BindTree()
        {
            //自定义菜单表,可以从XML或者数据库读取
            /*
            DataTable tblDatas = new DataTable("Datas");
            tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
            tblDatas.Columns.Add("Title", Type.GetType("System.String"));
            tblDatas.Columns.Add("Name", Type.GetType("System.String"));
            tblDatas.Columns.Add("ParentID", Type.GetType("System.Int32"));

            tblDatas.Rows.Add(new object[] { 1, "系统管理","" ,0 });
            tblDatas.Rows.Add(new object[] { 2, "电子制程管理","", 0 });
            tblDatas.Rows.Add(new object[] { 3, "菜单管理","Form1" ,1 });
            tblDatas.Rows.Add(new object[] { 4, "角色管理", "Form2",1 });
            tblDatas.Rows.Add(new object[] { 5, "用户授权", "Form2", 1 });
            */
           
            string strRid = "select WF_RoleId from users where id=" + userid;
            string rid = string.Empty;
            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.conn, CommandType.Text, strRid))
            {
                if (dr.Read())
                {
                    rid = dr["WF_RoleId"].ToString();
                }

            }
            string strSql = "select * from dbo.WinForm_MenuInfo where ID in (select distinct mid from WinForm_RoleMenu where rid in(" + rid + ")) order by SORTINDEX ASC";
            DataTable tblDatas = SqlHelper.ExecuteDataset(SqlHelper.conn, CommandType.Text, strSql).Tables[0];
        

            initParent(tblDatas);

        }

        //初始化根节点
        private void initParent(DataTable dt)
        {
            DataRow[] drs = dt.Select("PARENTID=-1");
            foreach (DataRow dr in drs)
            {
                TreeNode tn = new TreeNode();
                tn.Text = dr["NAME"].ToString();
                tn.ToolTipText = dr["FORMNAME"].ToString();
                tn.Tag = dr["ID"].ToString();
                //tn.ImageIndex = 1;

                this.trvMeun.Nodes.Add(tn);
                //初始化下级节点
                initLeaf(dt, tn);
            }
        }
        //初始化下级节点
        private void initLeaf(DataTable dt, TreeNode tn)
        {
            DataRow[] drs = dt.Select("PARENTID=" + tn.Tag as string);
            foreach (DataRow dr in drs)
            {
                TreeNode ctn = new TreeNode();
                ctn.Text = dr["NAME"].ToString();
                ctn.ToolTipText = dr["FORMNAME"].ToString();
                ctn.Tag = dr["ID"].ToString();
               // tn.ImageIndex = 1;
                tn.Nodes.Add(ctn);

                //递归调用,不断循环至叶节点
                initLeaf(dt, ctn);
            }
        }
        //双击关闭Tab
        private void MainTabControl_DoubleClick(object sender, EventArgs e)
        {


            //Point pt = new Point(e.X, e.Y);
            if (MainTabControl.TabCount > 0)
            {
                if (MainTabControl.TabCount > 0)
                {
                    this.MainTabControl.TabPages.Remove(MainTabControl.SelectedTab);
                }
            }

        }
        /// <summary>
        /// 双击节点打开窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvMeun_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;

            if (trvMeun.SelectedNode.Parent == null)
            {

            }
            else
            {
                if (!FindTabControl(node.Text.Trim()))
                {
                    ERPSystem.ModuleClass myfrm = new ModuleClass();
                    if (myfrm.Show_Form(node.Text.Trim(),node.ToolTipText.ToString().Trim()) != null)
                    {
                        this.MainTabControl.TabPages.Add(myfrm.Show_Form(node.Text.Trim(), node.ToolTipText.ToString().Trim()));
                        this.MainTabControl.SelectedIndex = this.MainTabControl.TabPages.Count - 1;

                    }
                    else
                    {
                       // MessageBox.Show("还在建设中...!", "ERROR");
                    }

                }
            }



        }
        /// <summary>
        /// 查询选项卡集合中是否存在同名选项卡
        /// </summary>
        private bool FindTabControl(string tabName)
        {
            bool flag = false;
            foreach (TabPage item in MainTabControl.TabPages)
            {
                if (item.Text == tabName)
                {
                    flag = true;
                }
            }

            return flag;

        }

    }
}

ModuleClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.Remoting;
namespace ERPSystem
{
    class ModuleClass
    {
        public TabPage Show_Form(string FormTitle,string FormName)
        {
            string strNameSpace = "ERPSystem";
            if (FormName != "")
            {

                ObjectHandle obj = Activator.CreateInstance(null, strNameSpace + "." + FormName);
                //obj.Unwrap返回被包装的对象
                Form frm = (Form)obj.Unwrap();
                return initFrom(frm, FormTitle);
            }
            else 
            {
                return null;
            }
            /*
            switch (FormTitle)
            {
                case "菜单管理":
                    string formname = "Form1";
                case "数据库磁盘使用情况":
                    ERPSystem.Form1 frm2 = new ERPSystem.Form1();
                    return initFrom(frm2, FormTitle);
                case "IO情况":
                    ERPSystem.Form1 frm3 = new ERPSystem.Form1();
                    return initFrom(frm3, FormTitle);
                case "作业状态":
                    ERPSystem.Form1 frm4 = new ERPSystem.Form1();
                    return initFrom(frm4, FormTitle);

                case "内存使用情况":
                    ERPSystem.Form1 frm5 = new ERPSystem.Form1();
                    return initFrom(frm5, FormTitle);
             
                default:
                    return null;

            }
            */
        }
        /// <summary>
        /// 表单动态加载到页签
        /// </summary>
        /// <param name="frm"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        private TabPage initFrom(Form frm, String Name)
        {
            if (!string.IsNullOrEmpty(Name))
            {
                frm.Text = Name;
                frm.TopLevel = false;
                TabPage tp = new TabPage(Name);
                frm.FormBorderStyle = FormBorderStyle.None;
                tp.Controls.Add(frm);
                frm.Dock = DockStyle.Fill;
                frm.Show();
                return tp;
            }
            else
            {
                return null;
            }

        }
    }
}

测试: