Click here to Skip to main content
15,885,546 members
Articles / Database Development / SQL Server / SQL Server 2008

Architecture Guide: Windows Forms, Generics, Auto-Mapper, Entity Framework, Framework Design, and many more..

Rate me:
Please Sign up or sign in to vote.
4.93/5 (39 votes)
12 Dec 2013CPOL15 min read 141.2K   3.8K   175  
Architecting a Windows Forms based system on top of a framework. This will help you develop a form based application faster.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Demo.Framework.Utilities
{
    public class NumericTextBox : TextBox
    {
        #region Enums

        /// <summary>
        /// A enum of reasons why a paste was rejected.
        /// </summary>
        public enum PasteRejectReasons
        {
            Unknown = 0,
            NoData,
            InvalidCharacter,
            Accepted
        }

        #endregion

        #region Constants

        /// <summary>
        /// Windows message that is sent when a paste event occurs.
        /// </summary>
        public const int WM_PASTE = 0x0302;

        #endregion

        #region Events

        /// <summary>
        /// Occurs whenever a KeyDown event is suppressed.
        /// </summary>
        public event EventHandler<KeyRejectedEventArgs> KeyRejected;

        /// <summary>
        /// Occurs whenever a paste attempt is suppressed.
        /// </summary>
        public event EventHandler<PasteEventArgs> PasteRejected;

        #endregion

        #region Private Variables

        /// <summary>
        /// The last Text of the control.
        /// </summary>
        private string defaultText;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the default value for the control.
        /// </summary>
        public string DefaultText
        {
            get { return defaultText; }
            set
            {
                string oldValue = defaultText;
                if (defaultText != value)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        defaultText = value;
                        if (Text == oldValue)
                            Text = defaultText;
                    }
                    else
                        throw new ArgumentOutOfRangeException(
                            "value", "The default text cannot be empty.");
                }
            }
        }

        // New Text property to enable a new default value.
        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public override string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        // New HorizontalAlignment property to enable a new default value.
        /// <summary>
        /// Gets or sets the horizontal alignment of the text.
        /// </summary>
        public new HorizontalAlignment TextAlign
        {
            get { return base.TextAlign; }
            set { base.TextAlign = value; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Creates a new instance of the NumericTextBox
        /// </summary>
        public NumericTextBox()
        {
            TextAlign = HorizontalAlignment.Right;
            defaultText = "0";
            Text = defaultText;
        }

        #endregion

        #region Overridden Methods

        /// <summary>
        /// Raises the OnGotFocus event.
        /// </summary>
        /// <param name="e">A System.EventArgs that contains the event data.</param>
        protected override void OnGotFocus(EventArgs e)
        {
            // Select all text everytime control gets focus.
            SelectAll();
            base.OnGotFocus(e);
        }

        bool allowSpace = false;

        // Restricts the entry of characters to digits (including hex), the negative sign,
        // the decimal point, and editing keystrokes (backspace).
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);

            NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
            string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
            string groupSeparator = numberFormatInfo.NumberGroupSeparator;
            string negativeSign = numberFormatInfo.NegativeSign;

            string keyInput = e.KeyChar.ToString();

            if (Char.IsDigit(e.KeyChar))
            {
                // Digits are OK
            }
            else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
             keyInput.Equals(negativeSign))
            {
                // Decimal separator is OK
            }
            else if (e.KeyChar == '\b')
            {
                // Backspace key is OK
            }
            //    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
            //    {
            //     // Let the edit control handle control and alt key combinations
            //    }
            else if (this.allowSpace && e.KeyChar == ' ')
            {

            }
            else
            {
                // Consume this invalid key and beep
                e.Handled = true;
                //    MessageBeep();
            }
        }

        public int IntValue
        {
            get
            {
                return Int32.Parse(this.Text);
            }
        }

        public decimal DecimalValue
        {
            get
            {
                return Decimal.Parse(this.Text);
            }
        }

        public bool AllowSpace
        {
            set
            {
                this.allowSpace = value;
            }

            get
            {
                return this.allowSpace;
            }
        }

        /// <summary>
        /// Raises the LostFocus event.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected override void OnLostFocus(EventArgs e)
        {
            if (string.IsNullOrEmpty(Text))
                Text = defaultText;
            base.OnLostFocus(e);
        }


        /// <summary>
        /// Receives Windows messages to optionally process.
        /// </summary>
        /// <param name="m">The Windows message to process.</param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_PASTE)
            {
                PasteEventArgs e = CheckPasteValid();
                if (e.RejectReason != PasteRejectReasons.Accepted)
                {
                    m.Result = IntPtr.Zero;
                    OnPasteRejected(e);
                    return;
                }
            }
            base.WndProc(ref m);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Checks if the data on the clipboard contains text that is valid.
        /// </summary>
        /// <returns>A PasteEventArgs instance containing the relevant data.</returns>
        private PasteEventArgs CheckPasteValid()
        {
            // Default values.
            PasteRejectReasons rejectReason = PasteRejectReasons.Accepted;
            string originalText = Text;
            string clipboardText = string.Empty;
            string textResult = string.Empty;

            try
            {
                clipboardText = Clipboard.GetText(TextDataFormat.Text);
                if (clipboardText.Length > 0) // Does clipboard contain text?
                {
                    // Store text value as it will be post paste assuming it is valid.
                    textResult = (
                        Text.Remove(SelectionStart, SelectionLength).Insert(SelectionStart, clipboardText));
                    foreach (char c in clipboardText) // Check for any non digit characters.
                    {
                        if (!char.IsDigit(c))
                        {
                            rejectReason = PasteRejectReasons.InvalidCharacter;
                            break;
                        }
                    }
                }
                else
                    rejectReason = PasteRejectReasons.NoData;
            }
            catch
            {
                rejectReason = PasteRejectReasons.Unknown;
            }
            return new PasteEventArgs(originalText, clipboardText, textResult, rejectReason);
        }

        #endregion

        #region Event Raise Methods

        /// <summary>
        /// Raises the KeyRejected event.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected virtual void OnKeyRejected(KeyRejectedEventArgs e)
        {
            EventHandler<KeyRejectedEventArgs> handler = KeyRejected;
            if (handler != null)
                handler(this, e);
        }

        /// <summary>
        /// Raises the PasteRejected event.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected virtual void OnPasteRejected(PasteEventArgs e)
        {
            EventHandler<PasteEventArgs> handler = PasteRejected;
            if (handler != null)
                handler(this, e);
        }

        #endregion

        #region EventArg Classes

        /// <summary>
        /// Event arguments class for the KeyRejected event.
        /// </summary>
        public class KeyRejectedEventArgs : EventArgs
        {
            #region Private Variables

            private Keys m_Key;

            #endregion

            #region Properties

            /// <summary>
            /// Gets the rejected key.
            /// </summary>
            public Keys Key
            {
                get { return m_Key; }
            }

            #endregion

            #region Constructor

            /// <summary>
            /// Creates a new instance of the KeyRejectedEventArgs class.
            /// </summary>
            /// <param name="key">The rejected key.</param>
            public KeyRejectedEventArgs(Keys key)
            {
                m_Key = key;
            }

            #endregion

            #region Overridden Methods

            /// <summary>
            /// Converts this KeyRejectedEventArgs instance into it's string representation.
            /// </summary>
            /// <returns>A string indicating the rejected key.</returns>
            public override string ToString()
            {
                return string.Format("Rejected Key: {0}", Key.ToString());
            }

            #endregion
        }

        /// <summary>
        /// Event arguments class for the PasteRejected event.
        /// </summary>
        public class PasteEventArgs : EventArgs
        {
            #region Private Variables

            private string m_OriginalText;
            private string m_ClipboardText;
            private string m_TextResult;
            private PasteRejectReasons m_RejectReason;

            #endregion

            #region Properties

            /// <summary>
            /// Gets the original text.
            /// </summary>
            public string OriginalText
            {
                get { return m_OriginalText; }
            }

            /// <summary>
            /// Gets the text from the clipboard.
            /// </summary>
            public string ClipboardText
            {
                get { return m_ClipboardText; }
            }

            /// <summary>
            /// Gets the resulting text.
            /// </summary>
            public string TextResult
            {
                get { return m_TextResult; }
            }

            /// <summary>
            /// Gets the reason for the paste rejection.
            /// </summary>
            public PasteRejectReasons RejectReason
            {
                get { return m_RejectReason; }
            }

            #endregion

            #region Constructor

            /// <summary>
            /// Creates a new instance of the PasteRejectedEventArgs class.
            /// </summary>
            /// <param name="originalText">The original textl.</param>
            /// <param name="clipboardText">The text from the clipboard.</param>
            /// <param name="textResult">The resulting text.</param>
            /// <param name="rejectReason">The reason for the paste rejection.</param>
            public PasteEventArgs(string originalText, string clipboardText, string textResult,
                PasteRejectReasons rejectReason)
            {
                m_OriginalText = originalText;
                m_ClipboardText = clipboardText;
                m_TextResult = textResult;
                m_RejectReason = rejectReason;
            }

            #endregion

            #region Overridden Methods

            /// <summary>
            /// Converts this PasteRejectedEventArgs instance into it's string representation.
            /// </summary>
            /// <returns>A string indicating the rejected reason.</returns>
            public override string ToString()
            {
                return string.Format("Rejected reason: {0}", RejectReason.ToString());
            }

            #endregion
        }

        #endregion
    }
}

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 Code Project Open License (CPOL)


Written By
Architect Virtusa Pvt. Ltd.
Sri Lanka Sri Lanka
In-depth coverage of Microsoft .Net, Cloud and many other cutting-edge Technologies.

- The Mandelbrot set – someone has called it the thumb-print of God – is one of the most beautiful and remarkable discoveries in the entire history of mathematics. My profile picture is generated with that equation.

You may contact Nirosh for Consultations, Code Reviews and Architecture Guide Workshops via c_nir*o*sh@hotmail.com (Remove * to use)



View Nirosh L.W.C.'s profile on LinkedIn


Other Links

Comments and Discussions