Customcontrol's backcolor issue

rahul kumar 605 Reputation points
2023-06-25T11:52:06.88+00:00

I have a customtextbox with the following declaration .

 public customtextbox()
        {
             this.BorderStyle = BorderStyle.None;
             InitializeComponent();
        }
        protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            this.BackColor = Color.Black;
            this.ForeColor = Color.White;
            // this.Select(0, 0);// code for dont selecting text 
        }

        protected override void OnLeave(EventArgs e)
        {
            base.OnLeave(e);
           // this.BackColor = change according to the color of the form  
            this.ForeColor = Color.Black;
        }


i am trying to guess how to set the backcolor of this textbox according to the form containing it . Thanks in advance

Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-06-26T06:07:30.2066667+00:00

    Hi @rahul kumar , Welcome to Microsoft Q&A.

    Do you mean that when the custom textbox control is dragged into the form, its background is automatically modified as the form background?

    You can modify in onparentchange event.

    Here I set the border to 3D, just for the convenience of display, modify it according to your own needs.

    using System;
    using System.Windows.Forms;
    
    namespace _6_xx_uc2
    {
        public partial class CustomTextBox : TextBox
        {
            public CustomTextBox()
            {
                this.BorderStyle = BorderStyle.Fixed3D;
                InitializeComponent();
            }
    
            protected override void OnPaint(PaintEventArgs pe)
            {
                base.OnPaint(pe);
            }
    
            protected override void OnParentChanged(EventArgs e)
            {
                base.OnParentChanged(e);
    
                if (this.Parent != null)
                {
                    this.BackColor = this.Parent.BackColor;
                }
            }
        }
    }
    
    

    6-26

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2023-06-25T12:49:41.85+00:00

    If the Form is the direct parent, you can do :

     this.BackColor = this.Parent.BackColor;
    

Your answer

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