using Autofac; using Bro.Common.Factory; using Bro.Common.Interface; using Bro.Common.Model; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing.Design; using System.Drawing.Printing; using System.Globalization; using System.IO.Ports; using System.Linq; using System.Windows.Forms; using System.Windows.Forms.Design; namespace Bro.Common.Helper { #region TypeConvert public class SerialPortConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List portNames = SerialPort.GetPortNames().ToList(); //if (portNames.Count == 0) //{ // portNames.Add("当前无可用串口"); //} return new StandardValuesCollection(portNames); } } public class ExcelTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List portNames = new List() { "Excel文件", "CSV文件" }; //if (portNames.Count == 0) //{ // portNames.Add("当前无可用串口"); //} return new StandardValuesCollection(portNames); } } public class BaudRateConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List bauds = new List() { "9600", "19200", "38400", "43000", "56000", "57600", "115200", }; return new StandardValuesCollection(bauds); } } public abstract class ComboBoxItemTypeConvert : TypeConverter { //private Hashtable hash = null; public Hashtable Hash { get; set; } = new Hashtable(); //{ // get // { // if (hash == null) // { // hash = GetConvertHash(); // } // return hash; // } // set => hash = value; //} public abstract Hashtable GetConvertHash(ITypeDescriptorContext context); public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { Hash = GetConvertHash(context); string[] ids = new string[Hash.Values.Count]; int i = 0; foreach (DictionaryEntry myDE in Hash) { ids[i++] = (myDE.Key).ToString(); } return new StandardValuesCollection(ids); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object v) { try { if (Hash.Count > 0) { if (v is string) { foreach (DictionaryEntry myDE in Hash) { if (myDE.Value.Equals((v.ToString()))) return myDE.Key; } } } } catch (Exception) { } return base.ConvertFrom(context, culture, v); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object v, Type destinationType) { try { if (Hash.Count > 0) { if (destinationType == typeof(string)) { foreach (DictionaryEntry myDE in Hash) { if (myDE.Key.Equals(v)) return myDE.Value.ToString(); } return ""; } } } catch (Exception) { } return base.ConvertTo(context, culture, v, destinationType); } } public class NoEditStringConvert : StringConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } } public class ComplexObjectConvert : StringConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { //return base.ConvertTo(context, culture, value, destinationType); if (value != null) { if (value is IComplexDisplay) { return (value as IComplexDisplay).GetDisplayText(); } else if (value is IEnumerable enumList) { string display = ""; bool iComplexDisplayMatch = false; var enumrator = enumList.GetEnumerator(); while (enumrator.MoveNext()) { if (enumrator.Current is IComplexDisplay d) { iComplexDisplayMatch = true; display += $"{d.GetDisplayText()} "; } } if (iComplexDisplayMatch) { return display.Trim(); } } { return JsonConvert.SerializeObject(value); } } else { return "NULL"; } } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value.ToString() != "NULL") { return JsonConvert.DeserializeObject(value.ToString()); } else { return null; } } } public class CollectionCountConvert : TypeConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is ICollection) { return (value as ICollection).Count.ToString(); } else { return base.ConvertTo(context, culture, value, destinationType); } } } public class SimpleCollectionConvert : TypeConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is IEnumerable) { return String.Join(",", (value as IEnumerable)); } return base.ConvertTo(context, culture, value, destinationType); } } public class ShortTimeConverter : StringConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is DateTime?) { if (value == null) { return ""; } else { return ((DateTime)value).ToString("mm:ss.fff"); } } else { return base.ConvertTo(context, culture, value, destinationType); } } } public class ShortTimeHHmmConverter : StringConverter { public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return DateTime.Parse(value.ToString()); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is DateTime?) { if (value == null) { return ""; } else { return ((DateTime)value).ToString("HH:mm"); } } else { return base.ConvertTo(context, culture, value, destinationType); } } } public class PrinterConverter : StringConverter { public string Filter { get; set; } public PrinterConverter() : base() { } public PrinterConverter(string filter) : base() { Filter = filter; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List printerList = new List(); foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称 { if (!string.IsNullOrWhiteSpace(Filter)) { if (sPrint.Contains("Deli")) { printerList.Add(sPrint); } } else { printerList.Add(sPrint); } } return new StandardValuesCollection(printerList); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } } #endregion #region UITypeEditor public class FoldDialogEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { // 可以打开任何特定的对话框   FolderBrowserDialog dialog = new FolderBrowserDialog(); if (dialog.ShowDialog().Equals(DialogResult.OK)) { return dialog.SelectedPath; } } return value; } } public class FileDialogEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { // 可以打开任何特定的对话框   OpenFileDialog dialog = new OpenFileDialog { AddExtension = false }; if (dialog.ShowDialog().Equals(DialogResult.OK)) { return dialog.FileName; } } return value; } } public class SaveFileDialogEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { // 可以打开任何特定的对话框   SaveFileDialog dialog = new SaveFileDialog(); if (dialog.ShowDialog().Equals(DialogResult.OK)) { return dialog.FileName; } } return value; } } public class PropertyObjectEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { Form form = new Form { FormBorderStyle = FormBorderStyle.SizableToolWindow, StartPosition = FormStartPosition.CenterParent, Text = context.PropertyDescriptor.DisplayName + "--" + context.PropertyDescriptor.Description }; PropertyGrid pg = new PropertyGrid { Dock = DockStyle.Fill, ToolbarVisible = false, SelectedObject = value }; form.Controls.Add(pg); form.ShowDialog(); value = pg.SelectedObject; return value; } return base.EditValue(context, provider, value); } } public class PropertyObjectDropDownEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { UserControl form = new UserControl { //form.FormBorderStyle = FormBorderStyle.SizableToolWindow; //form.StartPosition = FormStartPosition.CenterParent; Text = context.PropertyDescriptor.DisplayName + "--" + context.PropertyDescriptor.Description }; PropertyGrid pg = new PropertyGrid { Dock = DockStyle.Fill, ToolbarVisible = false, SelectedObject = value }; form.Controls.Add(pg); //form.ShowDialog(); edSvc.DropDownControl(form); value = pg.SelectedObject; return value; } return base.EditValue(context, provider, value); } } //public class DropDownEditor : UITypeEditor //{ // public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) // { // return UITypeEditorEditStyle.DropDown; // } //} public class SimpleCollectionEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { Form form = new Form { FormBorderStyle = FormBorderStyle.SizableToolWindow, StartPosition = FormStartPosition.CenterParent, Text = context.PropertyDescriptor.DisplayName + "--" + context.PropertyDescriptor.Description }; TextBox tbox = new TextBox { Dock = DockStyle.Fill, Multiline = true }; form.Controls.Add(tbox); if (value is List tList) { tList.ForEach(t => { tbox.AppendText(t.ToString()); tbox.AppendText("\r\n"); }); } form.ShowDialog(); List returnStrs = tbox.Text.Split(new char[] { '\r', '\n', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); switch (typeof(T).Name) { case "Int32": return returnStrs.ConvertAll(u => int.Parse(u)); case "Int16": return returnStrs.ConvertAll(u => short.Parse(u)); case "Int64": return returnStrs.ConvertAll(u => long.Parse(u)); case "Single": return returnStrs.ConvertAll(u => float.Parse(u)); case "Double": return returnStrs.ConvertAll(u => double.Parse(u)); case "String": return returnStrs; case "DateTime": return returnStrs.ConvertAll(u => DateTime.Parse(u)); } } return base.EditValue(context, provider, value); } } /// /// 用于对象的显示 /// public interface IComplexDisplay { string GetDisplayText(); } public class ComplexCollectionEditor : CollectionEditor where T : new() { protected override CollectionForm CreateCollectionForm() { var form = base.CreateCollectionForm(); var prop = form.GetType().GetField("propertyBrowser", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (prop != null) { if (prop.GetValue(form) is PropertyGrid grid) { grid.HelpVisible = true; grid.ToolbarVisible = false; } } return form; } protected override object CreateInstance(Type itemType) { return base.CreateInstance(itemType); } //protected override object[] GetItems(object editValue) //{ // return base.GetItems(editValue); //} //protected override object SetItems(object editValue, object[] value) //{ // return base.SetItems(editValue, value); //} //public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) //{ // return base.EditValue(context, provider, value); //} public ComplexCollectionEditor(Type type) : base(type) { } /// /// 限制一次选一个实例 /// /// protected override bool CanSelectMultipleInstances() { return false; } /// /// 指定创建的对象类型 /// /// protected override Type CreateCollectionItemType() { return typeof(T); } protected override string GetDisplayText(object value) { if (value is IComplexDisplay) { return (value as IComplexDisplay).GetDisplayText(); } return base.GetDisplayText(value); } //protected override void DestroyInstance(object instance) //{ // base.DestroyInstance(instance);//重要!自动删除组件的设计时代码! //} } public sealed class TimePickerEditor : UITypeEditor, IDisposable { IWindowsFormsEditorService editorService; readonly DateTimePicker picker = new DateTimePicker(); public TimePickerEditor() { picker.Format = DateTimePickerFormat.Custom; picker.CustomFormat = "HH:mm"; picker.ShowUpDown = true; } public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown;//显示下拉按钮 } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider != null) { editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; } if (editorService != null) { try { //if (value == null) //{ // picker.Value = DateTime.Parse("00:00" as string); //} //else //{ // picker.Value = DateTime.Parse(value.ToString()); //} picker.Value = Convert.ToDateTime(value); } catch (Exception) { picker.Value = DateTime.Now; } editorService.DropDownControl(picker); } return picker.Value; } public void Dispose() { picker.Dispose(); } } public class InitialConfigCollectionEditor : CollectionEditor where T : class, IInitialConfig, new() { protected override CollectionForm CreateCollectionForm() { var form = base.CreateCollectionForm(); var prop = form.GetType().GetField("propertyBrowser", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (prop != null) { if (prop.GetValue(form) is PropertyGrid grid) { grid.HelpVisible = true; grid.ToolbarVisible = false; } } return form; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (value is List list) { for (int i = 0; i < list.Count; i++) { string driverType = list[i].DriverType; if (!string.IsNullOrWhiteSpace(driverType)) { IInitialConfig initial = ConfigFactory.GetInitialConfig(driverType); initial.DataFrom(list[i]); list[i] = initial; } } return base.EditValue(context, provider, list); } return base.EditValue(context, provider, value); } public InitialConfigCollectionEditor(Type type) : base(type) { } /// /// 限制一次选一个实例 /// /// protected override bool CanSelectMultipleInstances() { return false; } /// /// 指定创建的对象类型 /// /// protected override Type CreateCollectionItemType() { return typeof(T); } protected override string GetDisplayText(object value) { if (value is IComplexDisplay) { return (value as IComplexDisplay).GetDisplayText(); } return base.GetDisplayText(value); } protected override void DestroyInstance(object instance) { base.DestroyInstance(instance);//重要!自动删除组件的设计时代码! } } public class DeviceTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List devices = DeviceFactory.GetAllSupportDeviceTypeNames(); devices.Insert(0, ""); return new StandardValuesCollection(devices); } } public class DeviceTypeConverter : DeviceTypeConverter where T : IDevice { public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { List devices = DeviceFactory.GetAllSupportDeviceTypeNames(typeof(T)); devices.Insert(0, ""); return new StandardValuesCollection(devices); } } public class DeviceInitialConfigEditor : UITypeEditor where T : class, IInitialConfig { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { Form form = new Form { FormBorderStyle = FormBorderStyle.SizableToolWindow, StartPosition = FormStartPosition.CenterParent, Text = context.PropertyDescriptor.DisplayName + "--" + context.PropertyDescriptor.Description }; PropertyGrid pg = new PropertyGrid { Dock = DockStyle.Fill, ToolbarVisible = false }; string driverType = (value as T).DriverType; if (!string.IsNullOrWhiteSpace(driverType)) { IInitialConfig initial = ConfigFactory.GetInitialConfig(driverType); initial.DataFrom(value); value = initial; } pg.SelectedObject = value; form.Controls.Add(pg); form.ShowDialog(); value = pg.SelectedObject; return value; } return base.EditValue(context, provider, value); } } #endregion }