WinForm窗體權限控制的簡單實現

一.創建兩張表this

//存放要控制的窗體控件spa

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
);code

//存放用戶的控件控制狀態orm

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
);blog

 二.寫個方法.並把方法放到From_Load中,ip

代碼裏傳入的參數是要控制的窗體和一個自定義的類,是提供用戶名和數據訪問的,可替換爲其它類get

功能:cmd

從表中取出窗體和用戶數據.string

在窗體的控件和菜單上循環匹配取出的數據有無要控制的控件,並按用戶設置進行設定it

        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);
                    }
                }
            }
        }


    }

 

五.寫個窗體選擇用戶

六,可擴展用戶角色,更靈活.

相關文章
相關標籤/搜索