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 > )
{
//默认可视不可用
form.Controls.Find(row["ControlName"].ToString(), true)[].Enabled = false;
form.Controls.Find(row["ControlName"].ToString(), true)[].Visible = true;
//设定用户设置
DataRow[] dtrow = dt.Select($@"FormFullName = '{(form.GetType().FullName)}' and ControlName = '{(row["ControlName"].ToString())}' and UserName = '{(login.UserId)}'");
if(dtrow.Count() > )
{
form.Controls.Find(dtrow[]["ControlName"].ToString(), true)[].Enabled = (bool)(dtrow[]["IsEnable"] ?? false);
form.Controls.Find(dtrow[]["ControlName"].ToString(), true)[].Visible = (bool)(dtrow[]["IsVisible"] ?? true); }
}
}
catch { }
//菜单控制
try
{
if (form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true).Length > )
{
//默认可视不可用
form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true)[].Enabled = false;
form.MainMenuStrip.Items.Find(row["ControlName"].ToString(), true)[].Visible = true;
//设定用户设置
DataRow[] dtrow = dt.Select($@"FormFullName = '{(form.GetType().FullName)}' and ControlName = '{(row["ControlName"].ToString())}' and UserName = '{(login.UserId)}'");
if (dtrow.Count() > )
{
form.MainMenuStrip.Items.Find(dtrow[]["ControlName"].ToString(), true)[].Enabled = (bool)(dtrow[]["IsEnable"] ?? false);
form.MainMenuStrip.Items.Find(dtrow[]["ControlName"].ToString(), true)[].Visible = (bool)(dtrow[]["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 > )
{
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 > )
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 > )
{
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 > -)
{
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 > )
AddMenuInList(tdd);
}
ToolStripMenuItem tsm = con as ToolStripMenuItem;
if (tsm != null)
{
dt2.Rows.Add(tsm.Text , tsm.Name); if (tsm.DropDownItems.Count > )
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 > )
AddMenuInList(tdd);
}
ToolStripMenuItem tsm = con as ToolStripMenuItem;
if (tsm != null)
{
dt2.Rows.Add(tsm.Text, tsm.Name); if (tsm.DropDownItems.Count > )
AddMenuInList(tsm);
}
}
}
} }
五.写个窗体选择用户
六,可扩展用户角色,更灵活.
WinForm窗体权限控制的简单实现的更多相关文章
- shiro权限控制的简单实现
权限控制常用的有shiro.spring security,两者相比较,各有优缺点,此篇文章以shiro为例,实现系统的权限控制. 一.数据库的设计 简单的五张表,用户.角色.权限及关联表: CREA ...
- ASP.NET MVC中权限控制的简单实现
1.重写AuthorizeAttribute类,用自己的权限控制逻辑重写AuthorizeCore方法 public class MyAuthorizeAttribute : AuthorizeAtt ...
- Kibana访问权限控制
ELK平台搭建完成后,由于Kibana的服务也是暴露在外网,且默认是没有访问限制的(外部所有人都可以访问到),这明显不是我们想要的,所以我们需要利用Nginx接管所有Kibana请求,通过Nginx配 ...
- SpringCloud微服务实战——搭建企业级开发框架(二十八):扩展MybatisPlus插件DataPermissionInterceptor实现数据权限控制
一套完整的系统权限需要支持功能权限和数据权限,前面介绍了系统通过RBAC的权限模型来实现功能的权限控制,这里我们来介绍,通过扩展Mybatis-Plus的插件DataPermissionInterce ...
- Winform开发框架之字段权限控制
在我的很多Winform开发项目中(包括混合框架的项目),统一采用了权限管理模块来进行各种权限的控制,包括常规的功能权限(按钮.菜单权限).数据权限(记录的权限),另外还可以进行字段级别的字段权限控制 ...
- WinForm下窗体权限设计
权限设计 笔者不才看了园子里面很多园友写关于权限设计这块内容,那么笔者也在添一笔.这个是笔者在上完软件工程课程后,上交的一篇笔者论文,这里分享给大家交流,当然笔者经验尚浅,若内容有误,请大家指点出 ...
- C#winform菜单权限分配,与菜单同步的treeView树状菜单权限控制使用心得
在网上查了很多,发现没有讲述关于--C#winform菜单权限分配,与菜单同步的treeView树状菜单权限控制使用--的资料 自己研究了一个使用方法.下面来看看. 我有两个窗体:LOGINFRM,M ...
- 基于SqlSugar的开发框架循序渐进介绍(9)-- 结合Winform控件实现字段的权限控制
字段的权限控制,一般就是控制对应角色人员对某个业务对象的一些敏感字段的可访问性:包括可见.可编辑性等处理.本篇随笔结合基于SqlSugar的开发框架进行的字段控制管理介绍. 在设计字段权限的时候,我们 ...
- WinForm窗体淡入效果界面的简单实现方法
WinForm窗体淡入效果主要使用到控件的Opacity属性 首先在WinForm窗体中拖入一个Timer控件,然后再Timer控件的Tick事件添加如下代码: private void timer1 ...
随机推荐
- # Do—Now——团队冲刺博客_总结篇
Do-Now--团队冲刺博客_总结篇 目录 博客链接 作者 1. 第一篇(领航篇) @仇夏 2. 第二篇 @侯泽洋 3. 第三篇 @仇夏 4. 第四篇 @周亚杰 5. 第五篇 @唐才铭 6. 第六篇 ...
- Qt写websocketpp服务端
1.下载websocketpp,地址为https://github.com/zaphoyd/websocketpp,版本为0.7. 2.下载boost,地址为https://www.boost.org ...
- 顺序表的原理与python中的list类型
数据是如何在内存中存储的? 在32位的计算机上,1个字节有8位,内存寻址的最小单位就是字节.假设我们有一个int类型的值,它从0x10开始,一个int占据4个字节,则其结束于0x13. 那么数据类型有 ...
- [LeetCode] K-th Symbol in Grammar 语法中的第K个符号
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace ...
- react-redux简单的记事本应用
首先给大家普及一个方法: let data = [ {id:1,text:'手机',check:false}, {id:2,text:'电脑',check:false}, {id:3,text:'平板 ...
- style样式不换行
style="white-space:nowrap;"不自动换行<font color="" size=""></font ...
- windows android ndk的某些编译工具报错乱码0x5 或拒绝访问05
在IDEA或者AndroidStudio的快捷方式上右键属性 > 兼容性 > 以管理员身份运行 解决问题.
- SQLServer 大小写敏感配置
设置表内大小写敏感 ALTER TABLE 表名 ) COLLATE Chinese_PRC_CI_AS --不区分大小写 ALTER TABLE tb ) COLLATE Chinese_PRC_C ...
- Random Forest总结
一.简介 RF = Bagging + Decision Tree 随机:数据采样随机,特征选择随机 森林:多个决策树并行放在一起 几个误区: 不是每棵树随机选择特征,而是每一个结点都随机选择固定数目 ...
- unittest报告出现dict() -> new empty dictionary错误解决办法
unittest报告出现dict() -> new empty dictionary错误解决办法 说一下原因,这是由于unittest中采用了ddt驱动. 由于版本问题导致 问题如图: 解决办 ...