Click here to Skip to main content
15,891,375 members
Articles / Programming Languages / C#

DataStorage: Store settings type-safe

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
8 Aug 2012GPL33 min read 26.2K   234   9  
Shows how to use the DataStorage classes to generate type-safe settings classes.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using System.ComponentModel;

namespace Aga.Controls.Tree.NodeControls
{
	public abstract class BaseTextControl : EditableControl
	{
		private TextFormatFlags _baseFormatFlags;
        private TextFormatFlags _formatFlags;
        private Pen _focusPen;
		private StringFormat _format;

		#region Properties

		private Font _font = null;
		public Font Font
		{
			get
			{
				if (_font == null)
					return Control.DefaultFont;
				else
					return _font;
			}
			set
			{
				if (value == Control.DefaultFont)
					_font = null;
				else
					_font = value;
			}
		}

		protected bool ShouldSerializeFont()
		{
			return (_font != null);
		}

		private HorizontalAlignment _textAlign = HorizontalAlignment.Left;
		[DefaultValue(HorizontalAlignment.Left)]
		public HorizontalAlignment TextAlign
		{
			get { return _textAlign; }
			set 
			{ 
				_textAlign = value;
				SetFormatFlags();
			}
		}

		private StringTrimming _trimming = StringTrimming.None;
		[DefaultValue(StringTrimming.None)]
		public StringTrimming Trimming
		{
			get { return _trimming; }
			set 
			{ 
				_trimming = value;
				SetFormatFlags();
			}
		}

		private bool _displayHiddenContentInToolTip = true;
		[DefaultValue(true)]
		public bool DisplayHiddenContentInToolTip
		{
			get { return _displayHiddenContentInToolTip; }
			set { _displayHiddenContentInToolTip = value; }
		}

		private bool _useCompatibleTextRendering = false;
		[DefaultValue(false)]
		public bool UseCompatibleTextRendering
		{
			get { return _useCompatibleTextRendering; }
			set { _useCompatibleTextRendering = value; }
		}

		#endregion

		protected BaseTextControl()
		{
			IncrementalSearchEnabled = true;
			_focusPen = new Pen(Color.Black);
			_focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;

			_format = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces);
			_baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.NoPrefix |
                           TextFormatFlags.PreserveGraphicsTranslateTransform;
			SetFormatFlags();
			LeftMargin = 3;
		}

		private void SetFormatFlags()
		{
			_format.Alignment = TextHelper.TranslateAligment(TextAlign);
			_format.Trimming = Trimming;

			_formatFlags = _baseFormatFlags | TextHelper.TranslateAligmentToFlag(TextAlign)
				| TextHelper.TranslateTrimmingToFlag(Trimming);
		}

		public override Size MeasureSize(TreeNodeAdv node, DrawContext context)
		{
			return GetLabelSize(node, context);
		}

		protected Size GetLabelSize(TreeNodeAdv node, DrawContext context)
		{
			return GetLabelSize(node, context, GetLabel(node));
		}

		protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label)
		{
			PerformanceAnalyzer.Start("GetLabelSize");
			CheckThread();
			Font font = GetDrawingFont(node, context, label);
			Size s = Size.Empty;
			if (UseCompatibleTextRendering)
				s = TextRenderer.MeasureText(label, font);
			else
			{
				SizeF sf = context.Graphics.MeasureString(label, font);
				s = Size.Ceiling(sf); 
			}
			PerformanceAnalyzer.Finish("GetLabelSize");

			if (!s.IsEmpty)
				return s;
			else
				return new Size(10, Font.Height);
		}

		protected Font GetDrawingFont(TreeNodeAdv node, DrawContext context, string label)
		{
			Font font = context.Font;
			if (DrawText != null)
			{
				DrawEventArgs args = new DrawEventArgs(node, context, label);
				args.Font = context.Font;
				OnDrawText(args);
				font = args.Font;
			}
			return font;
		}

		protected void SetEditControlProperties(Control control, TreeNodeAdv node)
		{
			string label = GetLabel(node);
			DrawContext context = new DrawContext();
			context.Font = control.Font;
			control.Font = GetDrawingFont(node, context, label);
		}

		public override void Draw(TreeNodeAdv node, DrawContext context)
		{
			if (context.CurrentEditorOwner == this && node == Parent.CurrentNode)
				return;

			PerformanceAnalyzer.Start("BaseTextControl.Draw");
			string label = GetLabel(node);
			Rectangle bounds = GetBounds(node, context);
			Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y,	
				bounds.Width, context.Bounds.Height);

			Brush backgroundBrush;
			Color textColor;
			Font font;
			CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label);

			if (backgroundBrush != null)
				context.Graphics.FillRectangle(backgroundBrush, focusRect);
			if (context.DrawFocus)
			{
				focusRect.Width--;
				focusRect.Height--;
				if (context.DrawSelection == DrawSelectionMode.None)
					_focusPen.Color = SystemColors.ControlText;
				else
					_focusPen.Color = SystemColors.InactiveCaption;
				context.Graphics.DrawRectangle(_focusPen, focusRect);
			}
			if (UseCompatibleTextRendering)
				TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags);
			else
				context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format);
			PerformanceAnalyzer.Finish("BaseTextControl.Draw");
		}

		private static Dictionary<Color, Brush> _brushes = new Dictionary<Color,Brush>();
		private static Brush GetFrush(Color color)
		{
			Brush br;
			if (_brushes.ContainsKey(color))
				br = _brushes[color];
			else
			{
				br = new SolidBrush(color);
				_brushes.Add(color, br);
			}
			return br;
		}

		private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label)
		{
			textColor = SystemColors.ControlText;
			backgroundBrush = null;
			font = context.Font;
			if (context.DrawSelection == DrawSelectionMode.Active)
			{
				textColor = SystemColors.HighlightText;
                backgroundBrush = SystemBrushes.Highlight;
			}
			else if (context.DrawSelection == DrawSelectionMode.Inactive)
			{
				textColor = SystemColors.ControlText;
                backgroundBrush = SystemBrushes.InactiveBorder;
			}
			else if (context.DrawSelection == DrawSelectionMode.FullRowSelect)
				textColor = SystemColors.HighlightText;

			if (!context.Enabled)
				textColor = SystemColors.GrayText;

			if (DrawText != null)
			{
				DrawEventArgs args = new DrawEventArgs(node, context, text);
				args.TextColor = textColor;
				args.BackgroundBrush = backgroundBrush;
				args.Font = font;

				OnDrawText(args);

				textColor = args.TextColor;
				backgroundBrush = args.BackgroundBrush;
				font = args.Font;
				label = args.Text;
			}
		}

		public string GetLabel(TreeNodeAdv node)
		{
			if (node != null && node.Tag != null)
			{
				object obj = GetValue(node);
				if (obj != null)
					return FormatLabel(obj);
			}
			return string.Empty;
		}

		protected virtual string FormatLabel(object obj)
		{
			return obj.ToString();
		}

		public void SetLabel(TreeNodeAdv node, string value)
		{
			SetValue(node, value);
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				_focusPen.Dispose();
				_format.Dispose();
			}
		}

		/// <summary>
		/// Fires when control is going to draw a text. Can be used to change text or back color
		/// </summary>
		public event EventHandler<DrawEventArgs> DrawText;
		protected virtual void OnDrawText(DrawEventArgs args)
		{
			if (DrawText != null)
				DrawText(this, args);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
pdfforge GbR
Germany Germany
Philip is a Software Architect with severaly years of experience. He studied business IT in the University of Wedel, Germany, and has reached his Masters degree in 2010. Back in 2002, he started his so far best-known software PDFCreator. The second developer joined two years later and since then, both constantly improve this piece of open source software.

Comments and Discussions