Share via

CustomTextbox

Vivek Dahiya 65 Reputation points
2023-10-29T08:12:12.88+00:00

I have used the code which was asked by the user @Pankaj tripathi . the original question was at https://learn.microsoft.com/en-us/answers/questions/1407230/customtextbox-not-adding-from-designer
I also have the same question regarding the how can i make the control to get the color of its parent on its initial startup . Also the first alphabet is always in uppercase .

   public partial class CustomTextBox : TextBox
    {
        private int maxCharacters;
       

        public int MaxCharacters
        {
            get { return maxCharacters; }
            set
            {
                maxCharacters = value;
                Text = Text.Length > maxCharacters ? Text.Substring(0, maxCharacters) : Text;
            }
        }

        private bool useUpper = false;

        public bool UseUpper
        {
            get { return useUpper; }
            set { useUpper = value; }
        }

        public CustomTextBox()
        {
            CustomTextBoxWork.AttachKeyEvent(this);
        }
    }

    class CustomTextBoxWork
    {
        private static Color originalBackColor;

      

        public static void AttachKeyEvent(TextBox txb)
        {
            txb.KeyDown += Txb_KeyDown;
            txb.LostFocus += Txb_LostFocus;
            originalBackColor = txb.Parent.BackColor; // Set the originalBackColor to the parent's back color
        }

        private static void Txb_KeyDown(object sender, KeyEventArgs e)
        {
            var txb = (TextBox)sender;
            if (e.KeyCode == Keys.Escape)
            {
                txb.Text = "";
            }
            if (e.KeyCode == Keys.Enter)
            {
                txb.BackColor = Color.Yellow; // Change the back color to a different color when Enter is pressed
                Control ctl = txb;
                while (ctl.Parent != null)
                {
                    var next = ctl.Parent.GetNextControl(ctl, true);
                    if (next != null)
                    {
                        next.Focus();
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                        return;
                    }
                    ctl = ctl.Parent;
                }
            }

            if (txb.UseUpper)
            {
                if (char.IsLetter(txb.Text[0]) && !char.IsUpper(txb.Text[0]))
                {
                    txb.Text = char.ToUpper(txb.Text[0]) + txb.Text.Substring(1);
                    txb.SelectionStart = txb.Text.Length;
                }

                for (int i = 1; i < txb.Text.Length; i++)
                {
                    if (char.IsWhiteSpace(txb.Text[i - 1]) && char.IsLetter(txb.Text[i]) && !char.IsUpper(txb.Text[i]))
                    {
                        txb.Text = txb.Text.Substring(0, i) + char.ToUpper(txb.Text[i]) + txb.Text.Substring(i + 1);
                        txb.SelectionStart = txb.Text.Length;
                    }
                }
            }
        }

        private static void Txb_LostFocus(object sender, EventArgs e)
        {
            var txb = (TextBox)sender;
            txb.BackColor = originalBackColor; // Revert back to the original back color (parent's back color) when focus is lost
        }
    }
}


but as he has the problem with adding in the form , i cannot even compile my version of the code . Please help me in correcting my version of code . Thanks in advance

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

KOZ6.0 6,810 Reputation points
2023-10-29T11:58:17.7133333+00:00

I haven't gotten all my questions answered yet, but I've fixed the parts that I think can be fixed. AttachKeyEvent has been renamed to AttachEvents.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

public partial class CustomTextBox : TextBox
{
    private int maxCharacters;

    public int MaxCharacters {
        get { return maxCharacters; }
        set {
            maxCharacters = value;
            Text = Text.Length > maxCharacters ? Text.Substring(0, maxCharacters) : Text;
        }
    }

    private bool useUpper = false;

    public bool UseUpper {
        get { return useUpper; }
        set { useUpper = value; }
    }

    public CustomTextBox() {
        CustomTextBoxWork.AttachEvents(this);
    }

    protected override void Dispose(bool disposing) {
        base.Dispose(disposing);
        CustomTextBoxWork.DetachEvents(this);
    }
}

class CustomTextBoxWork
{
    [ThreadStatic]
    [Obsolete]
    private static Dictionary<Control, Color> originalBackColors;

    // not use originalBackColors 
#pragma warning disable 0612

    public static Dictionary<Control, Color> OriginalBackColors {
        get {
            if (originalBackColors == null) {
                originalBackColors = new Dictionary<Control, Color>();
            }
            return originalBackColors;
        }
    }
#pragma warning restore 0612

    public static void AttachEvents(TextBox txb) {
        txb.KeyDown += Txb_KeyDown;
        txb.LostFocus += Txb_LostFocus;
        txb.ParentChanged += Txb_ParentChanged;
        txb.TextChanged += Txb_TextChanged;
    }

    public static void DetachEvents(TextBox txb) {
        txb.KeyDown -= Txb_KeyDown;
        txb.LostFocus -= Txb_LostFocus;
        txb.ParentChanged -= Txb_ParentChanged;
        txb.TextChanged -= Txb_TextChanged;
        if (OriginalBackColors.ContainsKey(txb)) {
            OriginalBackColors.Remove(txb);
        }
    }

    private static void Txb_ParentChanged(object sender, EventArgs e) {
        var txb = (TextBox)sender;
        if (txb.Parent != null) {
            OriginalBackColors[txb] = txb.Parent.BackColor;
            txb.BackColor = OriginalBackColors[txb];
        }
    }

    private static void Txb_KeyDown(object sender, KeyEventArgs e) {
        var txb = (TextBox)sender;
        if (e.KeyCode == Keys.Escape) {
            txb.Text = "";
        }
        if (e.KeyCode == Keys.Enter) {
            txb.BackColor = Color.Yellow; // Change the back color to a different color when Enter is pressed
            Control ctl = txb;
            while (ctl.Parent != null) {
                var next = ctl.Parent.GetNextControl(ctl, true);
                if (next != null) {
                    next.Focus();
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    return;
                }
                ctl = ctl.Parent;
            }
        }

    }

    private static void Txb_TextChanged(object sender, EventArgs e) {
        var txb = (CustomTextBox)sender;
        if (txb.UseUpper && txb.TextLength > 0) {
            string prevText = txb.Text;
            string nextText = ToUseUpper(prevText);
            if (nextText != prevText) {
                int selectionStart = txb.SelectionStart;
                int selectionLength = txb.SelectionLength;
                txb.Text = nextText;
                txb.Select(selectionStart, selectionLength);
            }
        }
    }

    private static string ToUseUpper(string text) {
        const string space = " ";
        var args = text.Split(space.ToCharArray());
        for (int i = 0; i < args.Length; i++) {
            if (!string.IsNullOrWhiteSpace(args[i])) {
                args[i] = char.ToUpper(args[i][0]) + args[i].Substring(1);
            }
        }
        return string.Join(space, args);
    }

    private static void Txb_LostFocus(object sender, EventArgs e) {
        var txb = (TextBox)sender;
        if (OriginalBackColors.TryGetValue(txb, out Color originalBackColor)) {
            txb.BackColor = originalBackColor;
        }
    }
}

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.