Click here to Skip to main content
15,886,570 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.1K   234   9  
Shows how to use the DataStorage classes to generate type-safe settings classes.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Globalization;


namespace Aga.Controls
{
	/// <summary>
	/// Restricts the entry of characters to digits, the negative sign,
	/// the decimal point, and editing keystrokes (backspace).
	/// It does not handle the AltGr key so any keys that can be created in any
	/// combination with AltGr these are not filtered
	/// </summary>
	public class NumericTextBox : TextBox
	{
		private const int WM_PASTE = 0x302;
		private NumberStyles numberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;

		/// <summary>
		/// Restricts the entry of characters to digits, the negative sign,
		/// the decimal point, and editing keystrokes (backspace).
		/// It does not handle the AltGr key
		/// </summary>
		/// <param name="e"></param>
		protected override void OnKeyPress(KeyPressEventArgs e)
		{
			base.OnKeyPress(e);

			e.Handled = invalidNumeric(e.KeyChar);
		}


		/// <summary>
		/// Main method for verifying allowed keypresses.
		/// This does not catch cut paste copy ... operations.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		private bool invalidNumeric(char key)
		{
			bool handled = false;

			NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
			string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
			string negativeSign = numberFormatInfo.NegativeSign;

			string keyString = key.ToString();

			if (Char.IsDigit(key))
			{
				// Digits are OK
			}
			else if (AllowDecimalSeperator && keyString.Equals(decimalSeparator))
			{
				if (Text.IndexOf(decimalSeparator) >= 0)
				{
					handled = true;
				}
			}
			else if (AllowNegativeSign && keyString.Equals(negativeSign))
			{
				if (Text.IndexOf(negativeSign) >= 0)
				{
					handled = true;
				}
			}
			else if (key == '\b')
			{
				// Backspace key is OK
			}
			else if ((ModifierKeys & (Keys.Control)) != 0)
			{
				// Let the edit control handle control and alt key combinations
			}
			else
			{
				// Swallow this invalid key and beep
				handled = true;
			}
			return handled;
		}


		/// <summary>
		/// Method invoked when Windows sends a message.
		/// </summary>
		/// <param name="m">Message from Windows.</param>
		/// <remarks>
		/// This is over-ridden so that the user can not use
		/// cut or paste operations to bypass the TextChanging event.
		/// This catches ContextMenu Paste, Shift+Insert, Ctrl+V,
		/// While it is generally frowned upon to override WndProc, no
		/// other simple mechanism was apparent to simultaneously and
		/// transparently intercept so many different operations.
		/// </remarks>
		protected override void WndProc(ref Message m)
		{
			// Switch to handle message...
			switch (m.Msg)
			{
				case WM_PASTE:
					{
						// Get clipboard object to paste
						IDataObject clipboardData = Clipboard.GetDataObject();

						// Get text from clipboard data
						string pasteText = (string)clipboardData.GetData(
								DataFormats.UnicodeText);

						// Get the number of characters to replace
						int selectionLength = SelectionLength;

						// If no replacement or insertion, we are done
						if (pasteText.Length == 0)
						{
							break;
						}
						else if (selectionLength != 0)
						{
							base.Text = base.Text.Remove(SelectionStart, selectionLength);
						}

						bool containsInvalidChars = false;
						foreach (char c in pasteText)
						{
							if (containsInvalidChars)
							{
								break;
							}
							else if (invalidNumeric(c))
							{
								containsInvalidChars = true;
							}
						}

						if (!containsInvalidChars)
						{
							base.Text = base.Text.Insert(SelectionStart, pasteText);
						}

						return;
					}

			}
			base.WndProc(ref m);
		}


		public int IntValue
		{
			get
			{
				int intValue;
				Int32.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out intValue);
				return intValue;
			}
		}

		public decimal DecimalValue
		{
			get
			{
				decimal decimalValue;
				Decimal.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out decimalValue);
				return decimalValue;
			}
		}


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

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

	}

}

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