Freigeben über


How to develop a readonly transparent Textbox control in Windows Forms

I saw several questions in MSDN forums asking for how to develop a transparent TextBox or RichTextBox control that is not only ReadOnly but also transparent and does not display a “caret” icon when clicked on it. He is some sample code that can get you started..

 public class TransparentTextBox : RichTextBox
    {
        public TransparentTextBox()
        {}

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams TransparentTextBoxParams = base.CreateParams;

                //0x20 for transparent style 
                TransparentTextBoxParams.ExStyle |= 0x20; 
                return TransparentTextBoxParams;
            }
        }

        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            //We dont want to paint anything in the back ground.
            //base.OnPaintBackground(pevent);
            //Do nothing
        }

     
        protected override void WndProc(ref Message message)
        {
            // Supress the below events (To hide the blinking caret in the RichTextBox)
            // WM_NCLBUTTONDOWN WM_LBUTTONUP WM_LBUTTONDOWN 
            // WM_LBUTTONDBLCLK WM_RBUTTONDOWN WM_RBUTTONUP WM_RBUTTONDBLCLK  
            if (!(base.ReadOnly && 
                  (message.Msg == 0xa1 || 
                   message.Msg == 0x201 || 
                   message.Msg == 0x202 || 
                   message.Msg == 0x203 || 
                   message.Msg == 0x204 || 
                   message.Msg == 0x205 || 
                   message.Msg == 0x206)))
                base.WndProc(ref message);
        }
    }

 

Happy Coding!

Comments

  • Anonymous
    July 15, 2008
    Sounds a lot like a label! I suppose there must be some reason for usining a TextBox instead.

  • Anonymous
    July 16, 2008
    Hi Doug, You are correct. But I think they are using RichTextBox to display some rtf text and needed to make it Readonly + Trasparent

  • Anonymous
    December 08, 2008
    Hi NandaL, I'd like to start by thanking you for the above sample. It really came in handy. I am a bit new to the WndProc() method and was curious what the best resource is for finding the numbers that correlate to the messages.

  • Anonymous
    December 09, 2008
    Justin, You should be able to find all the defined constants in WinUser.h, which is available through Windows SDK. You can download the latest SDK from http://msdn.microsoft.com/en-us/windows/bb980924.aspx. After installation all the header files are dropped into %ProgramFiles%Microsoft SDKsWindows%SDKVersion%Include folder. Thanks, Nanda