Winform窗体控件级权限处理
公共类:
static class PowerHelper
{
/// <summary>
/// 设置form上的组件的权限
/// </summary>
/// <param name="form">控件所在的窗体</param>
/// <param name="getPermissionsHandler">取得form里组件名及其Enabled属性(当前用户)的键值对</param>
public static void SetPermissions(this Form form, Func<Form, IDictionary<string, bool>> getPermissionsHandler)
{
Type t = form.GetType();
FieldInfo[] fs = t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
IDictionary<string, bool> permissions = getPermissionsHandler(form);
foreach (FieldInfo f in fs)
{
dynamic component = f.GetValue(form);
if (component is System.ComponentModel.Component && permissions.ContainsKey(f.Name))
{
try
{
//禁用
component.Enabled = permissions[f.Name];
//隐藏
//component.Visible = permissions[f.Name];
}
catch { }
}
}
}
基类窗体加入验证:
public partial class BaseForm : Form
{
public BaseForm()
{
InitializeComponent();
}
private void BaseForm_Load(object sender, EventArgs e)
{
Func<Form, IDictionary<string, bool>> powerFunc = ValidatePower;
PowerHelper.SetPermissions(this, powerFunc);
}
private Dictionary<string, bool> ValidatePower(Form frm)
{
Dictionary<string, bool> powerList = new Dictionary<string, bool>();
powerList.Add("toolStripButton1", false);
powerList.Add("button3", false);
powerList.Add("textBox2", false);
return powerList;
}
}
程序窗体继承基类:
public partial class Form1 : BaseForm
{
public Form1()
{
InitializeComponent();
}
}