#region using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Windows.Forms; using CSFrameworkV5.Business; using CSFrameworkV5.Common; using CSFrameworkV5.Core; using CSFrameworkV5.Language; using DevExpress.Utils.Menu; using DevExpress.XtraEditors.Controls; using DevExpress.XtraGrid.Menu; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraPrinting; using BorderSide = DevExpress.XtraPrinting.BorderSide; #endregion namespace CSFrameworkV5.Library { /// /// DevExpress表格样式配置窗体 /// public partial class frmGridCustomize : Form { /// /// 当前配置 /// private static GridLayoutConfig _Current; /// /// 所有表格配置 /// private static Hashtable _HashGridConfig; private frmGridCustomize() { InitializeComponent(); } #region 外部调用公开接口 /// /// 注册表格 /// /// 表格 /// 使用自定义表格样式 public static void RegisterGrid(GridView view, bool customGridStyle = true) { var config = new GridLayoutConfig(view, "Default"); config.CustomGridStyle = customGridStyle; RegistConfig(config); config.RestoreLayout(); //读取表格配置信息. } #endregion #region 窗体实例的方法定义 /// /// 加载样式表清单 /// /// private void LoadLayoutList(GridLayoutConfig current) { if (current != null) { _Current = current; lbCurrentLayout.Text = current.CurrentLayoutName; } //加载样式表 list.Items.Clear(); var tmp = current.GetLayoutNameList(); foreach (var O in tmp) list.Items.Add(O, 0); } //保存样式 private void btnSave_Click(object sender, EventArgs e) { if (list.SelectedItem == null) { MessageBox.Show("请选择一个样式!"); return; } var layoutName = ((list.SelectedItem as ImageListBoxItem) .Value as GridLayoutFile).Name; if (DialogResult.Yes == MessageBox.Show("确定要保存为<" + layoutName + ">表格样式吗?", "对话框", MessageBoxButtons.YesNo)) { _Current.SaveLayout(layoutName); Close(); } } //判断新增的样式是否存在 private bool IsExistsLayoutName(string layoutName) { foreach (ImageListBoxItem item in list.Items) if ((item.Value as GridLayoutFile).Name == layoutName) return true; return false; } //设置默认样式 private void btnDefault_Click(object sender, EventArgs e) { if (list.SelectedItem == null) { MessageBox.Show("请选择一个样式名称!"); return; } var layoutName = ((list.SelectedItem as ImageListBoxItem) .Value as GridLayoutFile).Name; _Current.SetDefault(layoutName); Msg.ShowInformation("设置默认样式成功,打开窗体时将默认加载此样式。"); Close(); } //加载样式 private void btnLoad_Click(object sender, EventArgs e) { if (list.SelectedItem == null) { MessageBox.Show("请选择一个样式名称!"); return; } var layoutName = ((list.SelectedItem as ImageListBoxItem) .Value as GridLayoutFile).Name; _Current.RestoreLayout(layoutName); Close(); } //删除样式 private void btnDel_Click(object sender, EventArgs e) { if (list.SelectedItem == null) return; var layoutName = ((list.SelectedItem as ImageListBoxItem) .Value as GridLayoutFile).Name; if (DialogResult.Yes == MessageBox.Show("确定要删除<" + layoutName + ">表格样式吗?", "对话框", MessageBoxButtons.YesNo)) { _Current.RemoveLayout(layoutName); LoadLayoutList(_Current); if (list.ItemCount == 0) lbCurrentLayout.Text = "无"; if (layoutName == lbCurrentLayout.Text) MessageBox.Show("您删除当前正在使用的表格样式,重新打开窗体才能生效!"); } } //新增样式 private void btnAdd_Click(object sender, EventArgs e) { //防止路径遍历 var layoutName = txtConfigName.Text.Replace("..", "") .Replace(@"\", "").Replace("/", ""); if (!string.IsNullOrWhiteSpace(layoutName)) { if (!IsExistsLayoutName(layoutName)) { _Current.SaveLayout(layoutName); LoadLayoutList(_Current); txtConfigName.Text = ""; txtConfigName.Focus(); } else { MessageBox.Show("样式名称不可重复!"); } } } #endregion #region 私有静态方法 /// /// 注册表格配置功能 /// /// private static void RegistConfig(GridLayoutConfig config) { //config.CreateDefaultLayout(); .. if (_HashGridConfig == null) _HashGridConfig = new Hashtable(); //重复注册表格,要删除原来的信息 var key = config.GetConfigName(); if (_HashGridConfig.ContainsKey(key)) _HashGridConfig.Remove(key); //同一个表格只能注册一个配置信息 foreach (var K in _HashGridConfig.Keys) if ((_HashGridConfig[K] as GridLayoutConfig).GridView == config.GridView) { _HashGridConfig.Remove(K); break; } _HashGridConfig.Add(key, config); //绑定弹出菜单,清除事件,避免重复添加 config.GridView.PopupMenuShowing -= OnShowGridMenu; config.GridView.PopupMenuShowing += OnShowGridMenu; } /// /// 在表格内点右键弹出菜单(菜单自动创建) /// private static void OnShowGridMenu(object sender, PopupMenuShowingEventArgs e) { var view = sender as GridView; //获取当前GridView的配置信息 _Current = GetConfigByGridView(view); if (_Current == null) return; //用户在表格列头、资料行、分组区域点击鼠标弹出菜单 if (GridMenuType.Column == e.MenuType && e.Menu != null) { var images = GetMenuImage(); //创建菜单项目 if (_Current.CustomGridStyle) { CreatePopupMenuItem(e.Menu, LanLib.Get("保存默认样式"), images.Images[0], OnClick_SaveCurrent, true); CreatePopupMenuItem(e.Menu, LanLib.Get("还原初始样式"), images.Images[2], OnClick_DeleteCurrent, false); CreatePopupMenuItem(e.Menu, LanLib.Get("样式管理器"), images.Images[1], OnClick_OpenConfirmForm, false); } CreatePopupMenuItem(e.Menu, LanLib.Get("打印文件"), images.Images[7], OnClick_PrintFile, true); //创建二级菜单 var E = new DXSubMenuItem(LanLib.Get("导出文件"), null); E.Image = images.Images[3]; E.BeginGroup = true; //分组 E.Items.Add(new DXMenuItem(LanLib.Get("导出Excel 97~2003文件"), OnClick_ExportXlsOld, images.Images[4])); E.Items.Add(new DXMenuItem(LanLib.Get("导出Excel 2007或以上版本"), OnClick_ExportXlsNew, images.Images[5])); E.Items.Add(new DXMenuItem(LanLib.Get("导出PDF文件"), OnClick_ExportPDF, images.Images[6])); e.Menu.Items.Add(E); } //扩展的菜单 if (e.Menu != null) { var list = (List)_ExtraMenuClick[view]; if (list != null) foreach (var menu in list) e.Menu.Items.Add(menu); } } private static void OnClick_PrintFile(object sender, EventArgs e) { var gc = _Current.GridView.GridControl; //绑定表格组件 var gv = _Current.GridView; gv.OptionsPrint.AutoWidth = false; //实例化打印组件 var link = new PrintableComponentLink(new PrintingSystem()); link.Component = gc; link.Landscape = true; link.PaperKind = PaperKind.A4; link.CreateMarginalHeaderArea += Link_CreateMarginalHeaderArea; link.CreateDocument(); link.ShowPreview(); } private static void Link_CreateMarginalHeaderArea(object sender, CreateAreaEventArgs e) { var gc = _Current.GridView.GridControl; //绑定表格组件 //LOGO using (Image logo = Globals.LoadBitmap("csframeworklog.jpg")) { e.Graph.DrawImage(logo, new RectangleF(0, 0, logo.Width, logo.Height), BorderSide.None, Color.White); } //报表标题 var title = gc.FindForm().Text; title = "《" + title + "》\r\n" + CommonData.CompanyInfo.NativeName; var brick = e.Graph.DrawPageInfo(PageInfo.None, title, Color.Black, new RectangleF(120, 0, 400, 60), BorderSide.None); brick.LineAlignment = BrickAlignment.Center; brick.Alignment = BrickAlignment.Center; brick.AutoWidth = false; brick.Font = new Font("黑体", 13f, FontStyle.Bold); //打印时间信息 var text = string.Format("打印人:{0} 打印时间:{1}", Loginer.CurrentUser.AccountName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); var P = new PageHeaderFooter(); P.Footer.Content.Add(text); P.Footer.LineAlignment = BrickAlignment.Center; (sender as PrintableComponentLink).PageHeaderFooter = P; _Current.GridView.OptionsPrint.AutoWidth = false; } /// /// 获取此表格的样式配置 /// /// 表格 /// private static GridLayoutConfig GetConfigByGridView(GridView view) { foreach (GridLayoutConfig o in _HashGridConfig.Values) if (o.GridView == view) return o; return null; } private static void OnClick_ExportXlsOld(object sender, EventArgs e) { if (_Current != null) { var dlg = new SaveFileDialog(); dlg.Filter = "Microsoft Office Excel 97~2003|*.xls"; if (dlg.ShowDialog() == DialogResult.OK) { _Current.GridView.ExportToXls(dlg.FileName); if (File.Exists(CodeSafeHelper.GetSafePath(dlg.FileName))) Msg.ShowInformation("导出文件" + dlg.FileName + "成功!"); else Msg.Warning("导出文件" + dlg.FileName + "失败!"); } } } private static void OnClick_ExportXlsNew(object sender, EventArgs e) { if (_Current != null) { var dlg = new SaveFileDialog(); dlg.Filter = "Microsoft Office Excel 2007或以上|*.xlsx"; if (dlg.ShowDialog() == DialogResult.OK) { _Current.GridView.ExportToXlsx(dlg.FileName); if (File.Exists(CodeSafeHelper.GetSafePath(dlg.FileName))) Msg.ShowInformation("导出文件" + dlg.FileName + "成功!"); else Msg.Warning("导出文件" + dlg.FileName + "失败!"); } } } private static void OnClick_ExportPDF(object sender, EventArgs e) { if (_Current != null) { var dlg = new SaveFileDialog(); dlg.Filter = "PDF格式文件|*.pdf"; if (dlg.ShowDialog() == DialogResult.OK) { _Current.GridView.ExportToPdf( CodeSafeHelper.GetSafePath(dlg.FileName)); Msg.ShowInformation("导出文件成功!文件名:" + dlg.FileName); } } } private static void OnClick_DeleteCurrent(object sender, EventArgs e) { if (_Current != null) if (Msg.AskQuestion("确定要还原为初始样式吗?")) { _Current.ResetLayout(); Msg.ShowInformation("请重新打开窗体使样式生效!"); } } private static void OnClick_OpenConfirmForm(object sender, EventArgs e) { if (_Current != null) { var form = new frmGridCustomize(); form.LoadLayoutList(_Current); form.ShowDialog(); } } private static void OnClick_SaveCurrent(object sender, EventArgs e) { if (_Current != null) { _Current.SetDefault(GridLayoutConfig.DEF_LAYOUT_NAME); _Current.SaveLayout(GridLayoutConfig.DEF_LAYOUT_NAME); Msg.ShowInformation("保存成功!"); } } private static ImageList _ImageListMenu; /// /// 获取菜单图标库 /// /// private static ImageList GetMenuImage() { if (_ImageListMenu == null) _ImageListMenu = new frmGridCustomize().imageList2; return _ImageListMenu; } /// /// 创建菜单项DXMenuItem /// /// GridViewMenu /// 菜单标题 /// 菜单图片 /// Click 事件 /// public static void CreatePopupMenuItem(GridViewMenu owner, string caption, Image image, EventHandler clickEvent, bool beginGroup) { var item = new DXMenuItem(caption); item.Image = image; item.Click += clickEvent; item.Tag = owner.View; //保存GridView引用,在DXMenuItem事件内快速找到GridView item.BeginGroup = beginGroup; owner.Items.Add(item); } #endregion #region AddMenuItem扩展方法,表格弹出菜单添加自定义菜单项 private static Hashtable _ExtraMenuClick = new Hashtable(); /// /// AddMenuItem扩展方法,表格弹出菜单添加自定义菜单项 /// /// GridView表格 /// 菜单标题 /// 菜单图片 /// click事件 /// 是否带分割线的菜单项 public static void AddMenuItem(GridView view, string caption, Image image, EventHandler clickEvent, bool beginGroup) { var list = (List)_ExtraMenuClick[view]; if (list == null) { list = new List(); _ExtraMenuClick.Add(view, list); } var item = new DXMenuItem(caption); item.Image = image; item.Click += clickEvent; item.Tag = view; //保存GridView引用,在DXMenuItem事件内快速找到GridView item.BeginGroup = beginGroup; list.Add(item); } #endregion } /// /// 表格配置类. /// internal class GridLayoutConfig { /*********************************************************** * 说明: * 1.一个表格支持多个配置,同时,一个窗体支持多个表格的配置 * 2.样式文件:GridLayoutCustomize.Form1.gridView1.Default.预设样式.xml * 3.表格全名:GridLayoutCustomize.Form1.gridView1 * 4.Default:预设配置名称,gridView1下可配置如:凭证格式,记账格式等 * 5.预设样式:为配置名称下一个样式,每个样式存储一个xml文件 ************************************************************/ internal const string DEF_LAYOUT_NAME = "预设样式"; private string _ConfigName = ""; private string _CurrentLayoutName = DEF_LAYOUT_NAME; private GridView _View; internal GridLayoutConfig(GridView view, string configName) { _View = view; _ConfigName = configName; _CurrentLayoutName = GetDefaultLayoutName(); } /// /// 本配置的当前样式名称 /// internal string CurrentLayoutName => _CurrentLayoutName; internal bool CustomGridStyle { get; set; } /// /// 表格对象 /// internal GridView GridView => _View; /// /// 创建预设样式配置文件(xml), 若文件已存在则不创建。 /// internal void CreateDefaultLayout() { var xmlFile = GetConfigFilePath(DEF_LAYOUT_NAME); if (!File.Exists(CodeSafeHelper.GetSafePath(xmlFile))) { SaveLayout(DEF_LAYOUT_NAME); SetDefault(DEF_LAYOUT_NAME); _CurrentLayoutName = DEF_LAYOUT_NAME; } } /// /// 删除配置文件 /// /// private void DeleteConfigFile(string xmlFile) { if (File.Exists(CodeSafeHelper.GetSafePath(xmlFile))) { SetFileAttributeNormal(xmlFile); File.Delete(CodeSafeHelper.GetSafePath(xmlFile)); } } /// /// 获取配置文件完整路径 /// /// private string GetConfigFilePath(string layoutName) { if (string.IsNullOrEmpty(layoutName)) layoutName = DEF_LAYOUT_NAME; var filePath = GetLayoutDirectory() + GetConfigName() + "." + layoutName + ".xml"; return filePath; } /// /// 获取表格配置名称 /// /// internal string GetConfigName() { var name = _View.GridControl.FindForm().GetType().FullName + "." + _View.Name + "." + _ConfigName; return name; } /// /// 获取预设加载的样式名称 /// /// internal string GetDefaultLayoutName() { var configName = GetConfigName(); var iniFile = GetLayoutDirectory() + "DefaultName.ini"; var ini = new IniFile(iniFile); return ini.IniReadValue("DefaultLayout", configName, ""); } /// /// 获取样式文件所在目录 /// /// private string GetLayoutDirectory() { var directory = Application.StartupPath + @"\Config\GridLayout\"; if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); return directory; } /// /// 获取当前配置的所有样式 /// /// internal List GetLayoutNameList() { var list = new List(); var defaultName = GetDefaultLayoutName(); var directory = GetLayoutDirectory(); var configName = GetConfigName(); var files = Directory.GetFiles( CodeSafeHelper.GetSafePath(directory), CodeSafeHelper.GetSafePath(configName + ".*.xml")); foreach (var file in files) { var layout = new GridLayoutFile(); layout.FileName = file; layout.FullName = Path.GetFileNameWithoutExtension(file); var i = layout.FullName.LastIndexOf('.'); layout.Name = layout.FullName.Substring(i + 1, layout.FullName.Length - i - 1); layout.CreateTime = File.GetCreationTime(CodeSafeHelper.GetSafePath(file)); layout.IsDefault = layout.Name == defaultName; list.Add(layout); } return list; } /// /// 删除样式 /// /// 样式名称 internal void RemoveLayout(string layoutName) { var xmlFile = GetConfigFilePath(layoutName); DeleteConfigFile(xmlFile); } /// /// 还原当前样式 /// internal void ResetLayout() { var xmlFile = GetConfigFilePath(DEF_LAYOUT_NAME); DeleteConfigFile(xmlFile); SetDefault(""); } /// /// 加载配置 /// internal void RestoreLayout() { RestoreLayout(_CurrentLayoutName); } /// /// 还原样式,加载样式 /// /// 样式名称 internal void RestoreLayout(string layoutName) { _CurrentLayoutName = layoutName; var xmlFile = GetConfigFilePath(layoutName); if (File.Exists(CodeSafeHelper.GetSafePath(xmlFile))) _View.RestoreLayoutFromXml(xmlFile); } /// /// 保存表格配置 /// internal void SaveLayout() { if (_CurrentLayoutName == "") { _CurrentLayoutName = DEF_LAYOUT_NAME; SetDefault(DEF_LAYOUT_NAME); } SaveLayout(_CurrentLayoutName); } /// /// 保存样式 /// /// 样式名称 internal void SaveLayout(string layoutName) { var xmlFile = GetConfigFilePath(layoutName); DeleteConfigFile(xmlFile); _View.SaveLayoutToXml(xmlFile); } /// /// 设置预设样式 /// /// 样式名称 internal void SetDefault(string layoutName) { var configName = GetConfigName(); var iniFile = GetLayoutDirectory() + "DefaultName.ini"; var ini = new IniFile(iniFile); ini.IniWriteValue("DefaultLayout", configName, layoutName); } /// /// 去掉文件只读属性 /// /// private void SetFileAttributeNormal(string aFilePath) { if (File.GetAttributes(CodeSafeHelper.GetSafePath(aFilePath)) .ToStringEx().IndexOf("ReadOnly") != -1) File.SetAttributes(CodeSafeHelper.GetSafePath(aFilePath), FileAttributes.Normal); } } /// /// 样式文件 /// internal class GridLayoutFile { internal GridLayoutFile() { Name = ""; FullName = ""; FileName = ""; IsDefault = false; } internal DateTime CreateTime { get; set; } internal string FileName { get; set; } internal string FullName { get; set; } internal bool IsDefault { get; set; } internal string Name { get; set; } public override string ToString() { return Name + " - 创建时间:" + CreateTime.ToString("yyyy/MM/dd HH:mm") + (IsDefault ? "(默认)" : ""); } } }