集结号娱乐中心官方网 当前位置:首页>集结号娱乐中心官方网>正文

集结号娱乐中心官方网

发布时间:2019-04-19

原标题:C#Winform设计的通用标签设计器

C#Winform设计的通用标签设计器


技术看点

  • PropertyGrid的使用
  • 自定义控件的使用
  • 对象序列化成XML
  • GDI+Windows驱动打印

前言

是的,一不小心把公司名称透露了。索性帮公司打一下广告。公司(上海易溯信息科技)是中国奶制品行业追溯生产管理方面的龙头。最近也是准备把业务拓展到东南亚地区,筹备走出国门。由于老系统的Windows驱动打印部分出现打印速度不够快,绘图精度不高,标签设计器简陋等问题。于是开始了重构,当然只是参考老程序的实现方式,程序是重新实现的。程序是用很零散的空闲时间写的,效果还需要在项目中实际运用,进行检验。

设计

由于一发现不熟悉的技术点就上网搜索,其实大部分技术难题都是搜索解决的。这里就不申明版权问题了,“如有雷同,纯属意外!”。哈哈

运行时读取模板数据,模板里标签的元素的设计

设计时可视化自定义控件的设计类图

编码实现

1)PropertyGrid的使用

代码都来自网络,主要就是属性名使用中文。使用英文对实施的电器工程师来说不太友好。

public delegate void PropertyChanged(object Value);
    /// <summary>
    /// 主要是实现中文化属性显示
    /// </summary>
    public class PropertyBase : ICustomTypeDescriptor
    {
        AttributeCollection ICustomTypeDescriptor.GetAttributes()
        {
            return TypeDescriptor.GetAttributes(this, true);
        }
        string ICustomTypeDescriptor.GetClassName()
        {
            return TypeDescriptor.GetClassName(this, true);
        }
        string ICustomTypeDescriptor.GetComponentName()
        {
            return TypeDescriptor.GetComponentName(this, true);
        }
        TypeConverter ICustomTypeDescriptor.GetConverter()
        {
            return TypeDescriptor.GetConverter(this, true);
        }
        EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
        {
            return TypeDescriptor.GetDefaultEvent(this, true);
        }
        PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
        {
            return null;
        }
        object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
        {
            return TypeDescriptor.GetEditor(this, editorBaseType, true);
        }
        EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
        {
            return TypeDescriptor.GetEvents(this, true);
        }
        EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
        {
            return TypeDescriptor.GetEvents(this, attributes, true);
        }
        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
        {
            return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
        }
        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
        {
            ArrayList props = new ArrayList();
            Type thisType = this.GetType();
            PropertyInfo[] pis = thisType.GetProperties();
            foreach (PropertyInfo p in pis)
            {
                if (p.DeclaringType == thisType || p.PropertyType.ToString() == "System.Drawing.Color")
                {
                    //判断属性是否显示
                    BrowsableAttribute Browsable = (BrowsableAttribute)Attribute.GetCustomAttribute(p, typeof(BrowsableAttribute));
                    if (Browsable != null)
                    {
                        if (Browsable.Browsable == true || p.PropertyType.ToString() == "System.Drawing.Color")
                        {
                            PropertyStub psd = new PropertyStub(p, attributes);
                            props.Add(psd);
                        }
                    }
                    else
                    {
                        PropertyStub psd = new PropertyStub(p, attributes);
                        props.Add(psd);
                    }
                }
            }
            PropertyDescriptor[] propArray = (PropertyDescriptor[])props.ToArray(typeof(PropertyDescriptor));
            return new PropertyDescriptorCollection(propArray);
        }
        object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
        {
            return this;
        }
    }

    /// <summary>
    /// 自定义属性拦截器
    /// </summary>
    public class PropertyStub : PropertyDescriptor
    {
        PropertyInfo info;
        public PropertyStub(PropertyInfo propertyInfo, Attribute[] attrs)
            : base(propertyInfo.Name, attrs)
        {
            info = propertyInfo;
        }
        public override Type ComponentType
        {
            get { return info.ReflectedType; }
        }
        public override bool IsReadOnly
        {
            get { return info.CanWrite == false; }
        }
        public override Type PropertyType
        {
            get { return info.PropertyType; }
        }
        public override bool CanResetValue(object component)
        {
            return false;
        }
        public override object GetValue(object component)
        {
            try
            {
                return info.GetValue(component, null);
            }
            catch
            {
                return null;
            }
        }
        public override void ResetValue(object component)
        {
        }
        public override void SetValue(object component, object value)
        {
            info.SetValue(component, value, null);
        }
        public override bool ShouldSerializeValue(object component)
        {
            return false;
        }
        //通过重载下面这个属性,可以将属性在PropertyGrid中的显示设置成中文
        public override string DisplayName
        {
            get
            {
                if (info != null)
                {
                    ChnPropertyAttribute uicontrolattibute = (ChnPropertyAttribute)Attribute.GetCustomAttribute(info, typeof(ChnPropertyAttribute));
                    if (uicontrolattibute != null)
                        return uicontrolattibute.PropertyName;
                    else
                    {
                        return info.Name;
                    }
                }
                else
                    return "";
            }
        }

        public override string Description
        {
            get
            {
                if (info != null)
                {
                    ChnPropertyAttribute uicontrolattibute = (ChnPropertyAttribute)Attribute.GetCustomAttribute(info, typeof(ChnPropertyAttribute));
                    if (uicontrolattibute != null)
                        return uicontrolattibute.PropertyDescription;
                }
                return string.Empty;
            }
        }
    }
自定义属性拦截器
/// <summary>
    /// 中文方式自定义属性标识
    /// </summary>
    public class ChnPropertyAttribute : Attribute
    {
        private string _PropertyName;
        private string _PropertyDescription;
        
        public ChnPropertyAttribute(string Name, string Description)
        {
            _PropertyName = Name;
            _PropertyDescription = Description;
        }
        public ChnPropertyAttribute(string Name)
        {
            _PropertyName = Name;
            _PropertyDescription = "";
        }
        public string PropertyName
        {
            get { return _PropertyName; }
        }
        public string PropertyDescription
        {
            get { return _PropertyDescription; }
        }
    }
自定义中文属性的Attribute

实际使用中文属性

2)自定义控件的使用

/// <summary>
    /// 标签最顶层容器,标签设计时容器
    /// </summary>
    [Serializable]
    public partial class RadiusRectangleSharp : Panel
    {
        #region 鼠标移动和缩放       
        const int Band = 5;
        const int MinWidth = 10;
        const int MinHeight = 10;
        private EnumMousePointPosition _mMousePointPosition;
        private Point _p, _p1;
        private EnumMousePointPosition MousePointPosition(Size size, System.Windows.Forms.MouseEventArgs e)
        {

            if ((e.X >= -1 * Band) | (e.X <= size.Width) | (e.Y >= -1 * Band) | (e.Y <= size.Height))
            {
                if (e.X < Band)
                {
                    if (e.Y < Band) { return EnumMousePointPosition.MouseSizeTopLeft; }
                    else
                    {
                        if (e.Y > -1 * Band + size.Height)
                        { return EnumMousePointPosition.MouseSizeBottomLeft; }
                        else
                        { return EnumMousePointPosition.MouseSizeLeft; }
                    }
                }
                else
                {
                    if (e.X > -1 * Band + size.Width)
                    {
                        if (e.Y < Band)
                        { return EnumMousePointPosition.MouseSizeTopRight; }
                        else
                        {
                            if (e.Y > -1 * Band + size.Height)
                            { return EnumMousePointPosition.MouseSizeBottomRight; }
                            else
                            { return EnumMousePointPosition.MouseSizeRight; }
                        }
                    }
                    else
                    {
                        if (e.Y < Band)
                        { return EnumMousePointPosition.MouseSizeTop; }
                        else
                        {
                            if (e.Y > -1 * Band + size.Height)
                            { return EnumMousePointPosition.MouseSizeBottom; }
                            else
                            { return EnumMousePointPosition.MouseDrag; }
                        }
                    }
                }
            }
            else
            { return EnumMousePointPosition.MouseSizeNone; }
        }
        #endregion               
        #region Local Variables       
        private Color _borderColor = Color.White;
        private int _radius = 8;
        private int _opacity = 68;
        private Color _dimmedColor = Color.LightGray;
        protected Rectangle IRect = new Rectangle();
        #endregion
        #region Properties        
        public Color BorderColor
        {
            get { return _borderColor; }
            set { _borderColor = value; Invalidate(); }
        }
        public int Opacity
        {
            get { return _opacity; }
            set { _opacity = value; this.Invalidate(); }
        }      
        public int Radius
        {
            get { return _radius; }
            set { _radius = value; this.Invalidate(); }
        }
        /// <summary>
        /// 当前模板信息
        /// </summary>
        public TemplateItemInfo CurrentTemplateInfo
        {
            get
            {
                return _currentTempletInfo;
            }
            set
            {
                _currentTempletInfo = value;
            }
        }
        private TemplateItemInfo _currentTempletInfo = new TemplateItemInfo();
        #endregion        
        public RadiusRectangleSharp()
        {
            InitializeComponent();
            AllowDrop = true;
            BackColor = Color.White;
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.Opaque, true);
            Margin = new Padding(1, 1, 1, 1);
            Padding = new Padding(0, 0, 0, 0);
            BorderColor = Color.DarkBlue;
            UpdateStyles();
            SendToBack();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            SmoothingMode sm = e.Graphics.SmoothingMode;
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.Clear(Color.White);
            DrawBorder(e.Graphics);
            DrawBackground(e.Graphics);
            e.Graphics.SmoothingMode = sm;
        }
        protected void DrawBorder(Graphics g)
        {
            Rectangle rect = ClientRectangle;
            rect.Width--;
            rect.Height--;
            using (GraphicsPath bp = GetPath(rect, _radius))
            {
                using (Pen p = new Pen(_borderColor))
                {
                    g.DrawPath(p, bp);
                }
            }
        }
        protected void DrawBackground(Graphics g)
        {
            Rectangle rect = ClientRectangle;
            IRect = rect;
            rect.X++;
            rect.Y++;
            rect.Width -= 2;
            rect.Height -= 2;
            using (GraphicsPath bb = GetPath(rect, _radius))
            {
                using (Brush br = new SolidBrush(Color.FromArgb(_opacity, BackColor)))
                {
                    g.FillPath(br, bb);
                }
            }
        }
        protected GraphicsPath GetPath(Rectangle rc, int r)
        {
            int x = rc.X, y = rc.Y, w = rc.Width, h = rc.Height;
            r = r << 1;
            GraphicsPath path = new GraphicsPath();
            if (r > 0)
            {
                if (r > h) { r = h; };                              //Rounded
                if (r > w) { r = w; };                              //Rounded
                path.AddArc(x, y, r, r, 180, 90);                    //Upper left corner
                path.AddArc(x + w - r, y, r, r, 270, 90);            //Upper right corner
                path.AddArc(x + w - r, y + h - r, r, r, 0, 90);        //Lower right corner
                path.AddArc(x, y + h - r, r, r, 90, 90);            //Lower left corner
                path.CloseFigure();
            }
            else
            {
                path.AddRectangle(rc);
            }
            return path;
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            _p.X = e.X;
            _p.Y = e.Y;
            _p1.X = e.X;
            _p1.Y = e.Y;
        }
        protected override void OnMouseUp(MouseEventArgs e)
        {
            _mMousePointPosition = EnumMousePointPosition.MouseSizeNone;
            this.Cursor = Cursors.Arrow;
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //本控件是顶层容器,不允许位移
                switch (_mMousePointPosition)
                {
                    #region 位置计算
                    case EnumMousePointPosition.MouseDrag:
                        break;
                    case EnumMousePointPosition.MouseSizeBottom:
                        Height = Height + e.Y - _p1.Y;
                        _p1.X = e.X;
                        _p1.Y = e.Y; //"记录光标拖动的当前点    
                        break;
                    case EnumMousePointPosition.MouseSizeBottomRight:
                        Width = Width + e.X - _p1.X;
                        Height = Height + e.Y - _p1.Y;
                        _p1.X = e.X;
                        _p1.Y = e.Y; //"记录光标拖动的当前点    
                        break;
                    case EnumMousePointPosition.MouseSizeRight:
                        Width = Width + e.X - _p1.X;
                        Height = Height + e.Y - _p1.Y;
                        _p1.X = e.X;
                        _p1.Y = e.Y; //"记录光标拖动的当前点    
                        break;
                    case EnumMousePointPosition.MouseSizeTop:
                        Height = Height - (e.Y - _p.Y);
                        break;
                    case EnumMousePointPosition.MouseSizeLeft:
                        Width = Width - (e.X - _p.X);
                        break;
                    case EnumMousePointPosition.MouseSizeBottomLeft:
                        Width = Width - (e.X - _p.X);
                        Height = Height + e.Y - _p1.Y;
                        _p1.X = e.X;
                        _p1.Y = e.Y; //"记录光标拖动的当前点    
                        break;
                    case EnumMousePointPosition.MouseSizeTopRight:
                        Width = Width + (e.X - _p1.X);
                        Height = Height - (e.Y - _p.Y);
                        _p1.X = e.X;
                        _p1.Y = e.Y; //"记录光标拖动的当前点    
                        break;
                    case EnumMousePointPosition.MouseSizeTopLeft:
                        Width = Width - (e.X - _p.X);
                        Height = Height - (e.Y - _p.Y);
                        break;
                    default:
                        break;
                        #endregion
                }
                if (Width < MinWidth) Width = MinWidth;
                if (Height < MinHeight) Height = MinHeight;
            }
            else
            {
                _mMousePointPosition = MousePointPosition(Size, e);
                switch (_mMousePointPosition)
                {
                    #region 改变光标
                    case EnumMousePointPosition.MouseSizeNone:
                        this.Cursor = Cursors.Arrow;        //"箭头    
                        break;
                    case EnumMousePointPosition.MouseDrag:
                        this.Cursor = Cursors.SizeAll;      //"四方向    
                        break;
                    case EnumMousePointPosition.MouseSizeBottom:
                        this.Cursor = Cursors.SizeNS;       //"南北    
                        break;
                    case EnumMousePointPosition.MouseSizeTop:
                        this.Cursor = Cursors.SizeNS;       //"南北    
                        break;
                    case EnumMousePointPosition.MouseSizeLeft:
                        this.Cursor = Cursors.SizeWE;       //"东西    
                        break;
                    case EnumMousePointPosition.MouseSizeRight:
                        this.Cursor = Cursors.SizeWE;       //"东西    
                        break;
                    case EnumMousePointPosition.MouseSizeBottomLeft:
                        this.Cursor = Cursors.SizeNESW;     //"东北到南西    
                        break;
                    case EnumMousePointPosition.MouseSizeBottomRight:
                        this.Cursor = Cursors.SizeNWSE;     //"东南到西北    
                        break;
                    case EnumMousePointPosition.MouseSizeTopLeft:
                        this.Cursor = Cursors.SizeNWSE;     //"东南到西北    
                        break;
                    case EnumMousePointPosition.MouseSizeTopRight:
                        this.Cursor = Cursors.SizeNESW;     //"东北到南西    
                        break;
                    default:
                        break;
                        #endregion
                }
            }
        }
        protected override void OnResize(EventArgs eventargs)
        {
            if (CurrentTemplateInfo != null)
            {
                CurrentTemplateInfo.Width = Size.Width;
                CurrentTemplateInfo.Height = Size.Height;
                Invalidate();
            }
        }
        protected override void OnDragEnter(DragEventArgs drgevent)
        {
            drgevent.Effect = DragDropEffects.Copy;
            base.OnDragEnter(drgevent);
        }
        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            try
            {
                string[] strs = (string[])drgevent.Data.GetData(typeof(string[])); //获取拖拽数据
                PictureBox ctrl = null;
                #region 实例化元素控件
                switch (strs.FirstOrDefault())
                {
                    case "Barcode":
                        ctrl = new BarcodePictureBox();
                        break;
                    case "Image":
                        ctrl = new ImagePictureBox();
                        break;
                    case "Text":
                        ctrl = new StaticTextBox();
                        break;
                    default:
                        break;
                }
                #endregion
                ctrl.Location = PointToClient(new Point(drgevent.X, drgevent.Y)); //屏幕坐标转换成控件容器坐标 
                ctrl.BringToFront();
                Controls.Add(ctrl);
            }
            catch (Exception ex)
            {
                string msg = "初始化控件出错!错误码:" + ex.Message + Environment.NewLine + ex.StackTrace;
                MessageTip.ShowError(this, msg, 3000);
            }
            base.OnDragDrop(drgevent);
        }
    }

整体上来说就是GDI+的使用,其中用了Base64编码来序列化图片。

3)对象序列化成XML

使用的是标准的方式:

/// <summary>
        /// 把对象序列化成xml文件
        /// </summary>
        /// <typeparam name="T">对象的类</typeparam>
        /// <param name="outFile">输出的文件和路径</param>
        /// <param name="t">对象的实例</param>
        public static void SerializerToXML<T>(string outFile, T t) where T : class
        {
            using (System.IO.FileStream fs = new System.IO.FileStream(outFile, System.IO.FileMode.Create))
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(fs, t, ns);
                fs.Flush();
            }
        }

        /// <summary>
        /// 从XML文件反序列化成集合对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="inXMLFile">xml的文件,全路径</param>
        /// <returns>对象集合</returns>
        public static T LoadFromXML<T>(string inXMLFile) where T : class
        {
            var t = default(T);
            using (System.IO.FileStream fs = new System.IO.FileStream(inXMLFile, System.IO.FileMode.Open))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                t = (T)xs.Deserialize(fs);
                fs.Close();
            }
            return t;
        }
 /// <summary>
    /// 图形元素
    /// </summary>
    [Serializable]
    public class ImageElementNode : PropertyBase, IElementNodeData, INotifyPropertyChanged
    {
        protected PictureBoxSizeMode _PictureBoxSizeMode = PictureBoxSizeMode.StretchImage;
        [ChnProperty("缩放模式", "图片原始尺寸和元素大小不一致时需要对原始图片进行缩放,设置缩放模式。")]
        [Category("通用属性")]
        public PictureBoxSizeMode ImageBoxSizeMode
        {
            get { return _PictureBoxSizeMode; }
            set { _PictureBoxSizeMode = value; }
        }

        private Point _location;
        [ChnProperty("位置", "节点元素的在模板里的位置的坐标,鼠标选中节点即可以移动位置。")]
        [Category("通用属性")]
        public Point Location
        {
            get { return _location; }
            set { _location = value; }
        }

        private string _name;
        [ChnProperty("元素名称", "一般自动生成,不需要维护。")]
        [Category("通用属性")]
        [XmlAttribute("Name")]
        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }

        [ChnProperty("元素节点类型", "模板元素节点类型,元素产生时根据添加时自动确定,设计时不要修改类型。"), Category("通用属性")]
        [XmlAttribute("NodeCategory")]
        public ElementNodeCategory NodeCategory
        {
            get { return ElementNodeCategory.静态文本; }
        }

        private ImageRoteType _roteDescription = ImageRoteType.正常;
        [ChnProperty("旋转角度", "变形的形态描述,比如顺时针旋转90度。"), Category("通用属性")]
        public ImageRoteType RoteDescription
        {
            get { return _roteDescription; }
            set { _roteDescription = value; NotifyPropertyChanged("RoteDescription"); }
        }

        private Size _size;
        [ChnProperty("元素大小", "包括高度和宽度,单位是像素。使用鼠标可调节大小,滚轮进行缩放。"), Category("通用属性")]
        public Size Size
        {
            get { return _size; }
            set { _size = value; }
        }

        [ChnProperty("静态表达式

当前文章://news65595/

发布时间:2019-04-19 01:03:13

手机登陆恒峰娱乐w ca88积分兑换商城 幻影娱乐登录网址 开元娱乐app唯一官网 鲸鱼娱乐主管46954 号百彩票 中乐彩网址 久发国际 乐虎官网 

责任编辑:顺马

随机推荐