3

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?

Reza Aghaei
  • 112,050
  • 16
  • 178
  • 345
AngryHacker
  • 56,860
  • 95
  • 305
  • 561

2 Answers2

6

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);
    }
}
Reza Aghaei
  • 112,050
  • 16
  • 178
  • 345
  • Also for a `TextBox`, you can refer to [this post](https://stackoverflow.com/a/4902969/3110834) or [this one](https://stackoverflow.com/a/36534068/3110834). – Reza Aghaei Jun 19 '18 at 03:21
  • Thanks for the solution. Since it is not so easy (or I did not find an easy way to do) to replace the inner control, you can also use the SendMessage approach from outside: _ = NativeMethods.SendMessage(tstbSearch.TextBox.Handle, NativeMethods.EM_SETCUEBANNER, 0, "Find..."); – TomB Mar 03 '22 at 11:28
  • @TomB of course you can. What I've done in this post is creating a ready to use MyToolStripTextBox so that you can have the feature in design-time as well. – Reza Aghaei Mar 03 '22 at 11:38
1

Have not tried myself.

But the Remarks section indicates you can manipulate the TextBox control directly.

ToolStripTextBox is the TextBox optimized for hosting in a ToolStrip. A subset of the hosted control's properties and events are exposed at the ToolStripTextBox level, but the underlying TextBox control is fully accessible through the TextBox property.

kennyzx
  • 12,605
  • 6
  • 36
  • 79