Search code examples
c#.netwinformstoolstrip

How to add placeholder text to ToolStripTextBox?


In a WinForms project, I know how to add placeholder text to a regular textbox. But the ToolStripTextBox doesn't appear to be a regular textbox. For one, it doesn't expose the handle (which is what's required to set the placeholder text via Win API).

So, how do I either set the placeholder text on a ToolStripTextBox or get its .Handle property?


Solution

  • ToolStripTextBox hosts a ToolStripTextBoxControl inside which is derived from TextBox and you can access the the hosted control using its TextBox or its Control property. So you can write such code:

    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    [ToolboxBitmap(typeof(ToolStripTextBox))]
    public class MyToolStripTextBox : ToolStripTextBox
    {
        private const int EM_SETCUEBANNER = 0x1501;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SendMessage(IntPtr hWnd, int msg,
            int wParam, string lParam);
        public MyToolStripTextBox()
        {
            this.Control.HandleCreated += Control_HandleCreated;
        }
        private void Control_HandleCreated(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cueBanner))
                UpdateCueBanner();
        }
        string cueBanner;
        public string CueBanner
        {
            get { return cueBanner; }
            set
            {
                cueBanner = value;
                UpdateCueBanner();
            }
        }
        private void UpdateCueBanner()
        {
            SendMessage(this.Control.Handle, EM_SETCUEBANNER, 0, cueBanner);
        }
    }