WinForm窗体权限控制的简单实现

一.建立两张表

//存放要控制的窗体控件

CREATE TABLE [dbo].[AuthControl] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[NiceName] VARCHAR (200) NULL,
[FormFullName] VARCHAR (200) NOT NULL,
[ControlName] VARCHAR (200) NOT NULL
);

//存放用户的控件控制状态

CREATE TABLE [dbo].[AuthUser] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[AuthControlID] INT NOT NULL,
[UserName] VARCHAR (50) NOT NULL,
[IsEnable] BIT NOT NULL,
[IsVisible] BIT NOT NULL
);

 二.写个方法.并把方法放到From_Load中,

代码里传入的参数是要控制的窗体和一个自定义的类,是提供用户名和数据访问的,可替换为其它类

功能:

从表中取出窗体和用户数据.

在窗体的控件和菜单上循环匹配取出的数据有无要控制的控件,并按用户设置进行设定

        public static void AuthUserControl(System.Windows.Forms.Form form, HRBase.UserRight login)
        {
            HRBase.UserRight.DataBaseOperate DB = (HRBase.UserRight.DataBaseOperate)login.NewDataBase("wsprint", "WERP", HRBase.UserRight.DataBaseOperate.Debug.Formal);
            string cmd = $@"select * 
                            from AuthControl a 
                            left join AuthUser b on a.id = b.AuthControlID 
                            where a.FormFullName = '{(form.GetType().FullName)}'";
            DataTable dt = DB.SelectToTable(cmd);
            //有行时才控制
            foreach (DataRow row in dt.Rows)
            {
                //Control控制
                try
                {
                    if (form.Controls.Find(row["ControlName"].ToString(), true).Length > 0)
                    {
                        //默认可视不可用
                        form.Controls.Find(row["ControlName"].ToString(), true)[0].Enabled =  false;
                        form.Controls.Find(row["ControlName"].ToString(), true)[0].Visible = true;
                        //设定用户设置
                        DataRow[] dtrow = dt.Select($@"FormFullName = '{(form.GetType().FullName)}' and ControlName = '{(row["ControlName"].ToString())}' and UserName = '{(login.UserId)}'");
                        if(dtrow.Count() > 0)
                        {
                            form.Controls.Find(dtrow[0]["ControlName"].ToString(), true)[0].Enabled = (bool)(dtrow[0]["IsEnable"] ?? false);
                            form.Controls.Find(dtrow[0]["ControlName"].ToString(), true)[0].Visible = (bool)(dtrow[0]["IsVisible"] ?? true);

                        }
                    }
                }
                catch { }
                //菜单控制
                try
                {
                    if (form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true).Length > 0)
                    {
                        //默认可视不可用
                        form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true)[0].Enabled =  false;
                        form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true)[0].Visible = true;
                        //设定用户设置
                        DataRow[] dtrow = dt.Select($@"FormFullName = '{(form.GetType().FullName)}' and ControlName = '{(row["ControlName"].ToString())}' and UserName = '{(login.UserId)}'");
                        if (dtrow.Count() > 0)
                        {
                            form.MainMenuStrip.Items.Find(dtrow[0]["ControlName"].ToString(), true)[0].Enabled = (bool)(dtrow[0]["IsEnable"] ?? false);
                            form.MainMenuStrip.Items.Find(dtrow[0]["ControlName"].ToString(), true)[0].Visible = (bool)(dtrow[0]["IsVisible"] ?? true);

                        }

                    }
                }
                catch { }
            }
        }

三.写个窗体用来保存权限数据

以下可选做

四,可以在通过反射namespace,获取窗体名和窗体的控件名

    public partial class SelectAuthControlForm : Form
    {
        DataTable dt1=new DataTable(), dt2 = new DataTable();
        /// <summary>
        /// 选择的窗体FullName
        /// </summary>
        /// <value>The full name of the select form.</value>
        public string SelectFormFullName { get;private set; }
        /// <summary>
        /// 选择的窗体上的控件Name
        /// </summary>
        /// <value>The name of the select control.</value>
        public string SelectControlName { get;private set; }

        public SelectAuthControlForm()
        {
            InitializeComponent();
            dt1.Columns.Add("Text");
            dt1.Columns.Add("FullName");
            dt2.Columns.Add("Text");
            dt2.Columns.Add("Name");
        }

        private void SelectAuthControlForm_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this.Show();
            dataGridView1.AddColumn("Text", "窗体标题");
            dataGridView1.AddColumn("FullName", "窗体类名");
            dataGridView2.AddColumn("Text", "控件文本");
            dataGridView2.AddColumn("Name", "控件类名");
            Application.DoEvents();
            var classes = Assembly.Load("erp").GetTypes();
            foreach (var item in classes)
            {
                if ((item.BaseType != null ? item.BaseType.Name : "") == "Form")
                {
                    try
                    {
                        var obj = Assembly.Load("erp").CreateInstance(item.FullName);
                        PropertyInfo propertyText = obj.GetType().GetProperty("Text"); //获取指定名称的属性
                        string valueText = propertyText.GetValue(obj, null).ToString(); //获取属性值
                        DataRow row = dt1.Rows.Add(valueText, item.FullName);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                    }
                }
            }
            dataGridView1.SetDataSource(dt1);

            this.Cursor = Cursors.Arrow;
            Application.DoEvents();
        }
        private void AddTabControl(TabPage page)
        {
            foreach (Control con in page.Controls)
            {
                Type type = con.GetType();
                string str1 = con.GetType().GetProperty("Text").GetValue(con, null).ToString();
                string strname1 = con.GetType().GetProperty("Name").GetValue(con, null).ToString();
                if (((Control)con).Controls.Count > 0)
                {
                    AddControlInList(type.FullName);
                }
                else
                {
                    PropertyInfo propertyText = con.GetType().GetProperty("Text"); //获取指定名称的属性
                    string valueText = propertyText.GetValue(con, null).ToString(); //获取属性值
                    PropertyInfo propertyName = con.GetType().GetProperty("Name"); //获取指定名称的属性
                    string valueName = propertyName.GetValue(con, null).ToString(); //获取属性值
                    dt2.Rows.Add(con.Text, con.Name);
                }

            }
        }
        private void AddControlInList(string fullName)
        {
            var obj = Assembly.Load("erp").CreateInstance(fullName);
            if (obj == null) return;
            foreach (Control con in ((Control)obj).Controls)
            {
                Type type = con.GetType();
                if(type.FullName == "System.Windows.Forms.TabControl")
                {
                    foreach(TabPage page in ((TabControl)con).TabPages)
                    {
                        AddTabControl(page);
                    }
                }
                switch (type.BaseType.Name)
                {
                    case "ToolStrip":
                        string str = con.GetType().GetProperty("Text").GetValue(con, null).ToString();
                        string strname = con.GetType().GetProperty("Name").GetValue(con, null).ToString();
                        if (((ToolStrip)con).Items.Count > 0)
                            AddMenuInList((ToolStrip)con);
                        else
                        {
                            dt2.Rows.Add(con.Text, con.Name);
                        }
                        break;
                    default:
                        string str1 = con.GetType().GetProperty("Text").GetValue(con, null).ToString();
                        string strname1 = con.GetType().GetProperty("Name").GetValue(con, null).ToString();
                        if (((Control)con).Controls.Count > 0)
                        {
                            AddControlInList(type.FullName);
                        }
                        else
                        {
                            PropertyInfo propertyText = con.GetType().GetProperty("Text"); //获取指定名称的属性
                            string valueText = propertyText.GetValue(con, null).ToString(); //获取属性值
                            PropertyInfo propertyName = con.GetType().GetProperty("Name"); //获取指定名称的属性
                            string valueName = propertyName.GetValue(con, null).ToString(); //获取属性值
                            dt2.Rows.Add(con.Text, con.Name);
                        }

                        break;
                }
            }

        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            dt2.Rows.Clear();
            if (e.RowIndex > -1)
            {
                string fillName = dataGridView1["FullName", e.RowIndex].Value.ToString();
                this.Cursor = Cursors.WaitCursor;
                AddControlInList(fillName);
                dataGridView2.SetDataSource(dt2);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null && dataGridView2.CurrentRow != null)
            {
                this.DialogResult = DialogResult.OK;
                SelectFormFullName = dataGridView1["FullName", dataGridView1.CurrentRow.Index].Value.ToString();
                SelectControlName = dataGridView2["Name", dataGridView2.CurrentRow.Index].Value.ToString();
            }
            else
            {
                MessageBox.Show("没有选择有效的控件!!!");
            }
        }

        private void AddMenuInList(object obj)
        {
            ToolStrip ts = obj as ToolStrip;
            if (ts != null)
            {
                foreach (object con in ts.Items)
                {
                    ToolStripDropDown tdd = con as ToolStripDropDown;
                    if (tdd != null)
                    {
                        dt2.Rows.Add(tdd.Text , tdd.Name);
                        if (tdd.Items.Count > 0)
                            AddMenuInList(tdd);
                    }
                    ToolStripMenuItem tsm = con as ToolStripMenuItem;
                    if (tsm != null)
                    {
                        dt2.Rows.Add(tsm.Text , tsm.Name);

                        if (tsm.DropDownItems.Count > 0)
                            AddMenuInList(tsm);
                    }
                }
            }
            ToolStripMenuItem ts1 = obj as ToolStripMenuItem;
            if (ts1 != null)
            {
                foreach (object con in ts1.DropDownItems)
                {
                    ToolStripDropDown tdd = con as ToolStripDropDown;
                    if (tdd != null)
                    {
                        dt2.Rows.Add(tdd.Text, tdd.Name);

                        if (tdd.Items.Count > 0)
                            AddMenuInList(tdd);
                    }
                    ToolStripMenuItem tsm = con as ToolStripMenuItem;
                    if (tsm != null)
                    {
                        dt2.Rows.Add(tsm.Text, tsm.Name);

                        if (tsm.DropDownItems.Count > 0)
                            AddMenuInList(tsm);
                    }
                }
            }
        }


    }

五.写个窗体选择用户

六,可扩展用户角色,更灵活.

原文地址:https://www.cnblogs.com/zhiming99/p/7363473.html