一.建立两张表

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

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窗体权限控制的简单实现的更多相关文章

  1. shiro权限控制的简单实现

    权限控制常用的有shiro.spring security,两者相比较,各有优缺点,此篇文章以shiro为例,实现系统的权限控制. 一.数据库的设计 简单的五张表,用户.角色.权限及关联表: CREA ...

  2. ASP.NET MVC中权限控制的简单实现

    1.重写AuthorizeAttribute类,用自己的权限控制逻辑重写AuthorizeCore方法 public class MyAuthorizeAttribute : AuthorizeAtt ...

  3. Kibana访问权限控制

    ELK平台搭建完成后,由于Kibana的服务也是暴露在外网,且默认是没有访问限制的(外部所有人都可以访问到),这明显不是我们想要的,所以我们需要利用Nginx接管所有Kibana请求,通过Nginx配 ...

  4. SpringCloud微服务实战——搭建企业级开发框架(二十八):扩展MybatisPlus插件DataPermissionInterceptor实现数据权限控制

    一套完整的系统权限需要支持功能权限和数据权限,前面介绍了系统通过RBAC的权限模型来实现功能的权限控制,这里我们来介绍,通过扩展Mybatis-Plus的插件DataPermissionInterce ...

  5. Winform开发框架之字段权限控制

    在我的很多Winform开发项目中(包括混合框架的项目),统一采用了权限管理模块来进行各种权限的控制,包括常规的功能权限(按钮.菜单权限).数据权限(记录的权限),另外还可以进行字段级别的字段权限控制 ...

  6. WinForm下窗体权限设计

    权限设计   笔者不才看了园子里面很多园友写关于权限设计这块内容,那么笔者也在添一笔.这个是笔者在上完软件工程课程后,上交的一篇笔者论文,这里分享给大家交流,当然笔者经验尚浅,若内容有误,请大家指点出 ...

  7. C#winform菜单权限分配,与菜单同步的treeView树状菜单权限控制使用心得

    在网上查了很多,发现没有讲述关于--C#winform菜单权限分配,与菜单同步的treeView树状菜单权限控制使用--的资料 自己研究了一个使用方法.下面来看看. 我有两个窗体:LOGINFRM,M ...

  8. 基于SqlSugar的开发框架循序渐进介绍(9)-- 结合Winform控件实现字段的权限控制

    字段的权限控制,一般就是控制对应角色人员对某个业务对象的一些敏感字段的可访问性:包括可见.可编辑性等处理.本篇随笔结合基于SqlSugar的开发框架进行的字段控制管理介绍. 在设计字段权限的时候,我们 ...

  9. WinForm窗体淡入效果界面的简单实现方法

    WinForm窗体淡入效果主要使用到控件的Opacity属性 首先在WinForm窗体中拖入一个Timer控件,然后再Timer控件的Tick事件添加如下代码: private void timer1 ...

随机推荐

  1. 转 InnoDB Error Handling

    14.20.4 InnoDB Error Handling Error handling in InnoDB is not always the same as specified in the SQ ...

  2. 数据库交互之减少IO次数

    一个对程序有要求的人一定会尽量去想办法减少IO次数来减少响应时间,但是又不能一味地为了减少IO次数而一直占用连接池.数据库连接一开一关也是需要耗费时间的,下面以SqlServer为例列举几种常见的减少 ...

  3. poj3045 Cow Acrobats(二分最大化最小值)

    https://vjudge.net/problem/POJ-3045 读题后提取到一点:例如对最底层的牛来说,它的崩溃风险=所有牛的重量-(底层牛的w+s),则w+s越大,越在底层. 注意范围lb= ...

  4. CSS3_移动端_开机动画

    移动端的 开机动画 <meta name="viewport" content="width=device-width, initial-scale=1, user ...

  5. ES6 promise学习

    Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大. 1.promise是一构造函数,既然是构造函数,那么我们就可以用 new Promise()得到一个p ...

  6. MacBook Air 装win10系统 by DODUI

    为了给齐哥更完美的体验Windows10系统,DODUI亲手操刀MacBook双系统安装Win10,双系统安装教程如下: 终于遇到各种奇葩问题,给小伙伴分享一下. 双系统安装Win10准备工具: 1. ...

  7. OO第二次阶段性总结

    前两次作业我都无效了……用了很久时间但还是没能弄明白多线程的写法,以后还是要学会即时的多问问会的同学吧…… 以及我的Mertrics在挣扎很久之后还是用不了……跪了 第七次作业 第七次作业能够完成的原 ...

  8. jquery $.ajax({});参数详解

    用到过的: type:请求方式,默认 GET: url:请求路径: data:请求参数,类型是String:JSON.stringify({"name":tom,"age ...

  9. WithOne 实体关系引起 EF Core 自动删除数据

    最近遇到了一个 EF Core 的恐怖问题,在添加数据时竟然会自动删除数据库中已存在的数据,经过追查发现是一个多余的实体关系配置引起的. modelBuilder.Entity<Question ...

  10. iOS开发支付篇-内购(IAP)

    一,前言 经典文章参考: . http://yimouleng.com/2015/12/17/ios-AppStore/ 内购流程 . http://www.jianshu.com/p/b199a46 ...