如何将占位符文本添加到 ToolStripTextBox?

How to add placeholder text to ToolStripTextBox?

在 WinForms 项目中,我知道如何将 placeholder text 添加到常规文本框。但 ToolStripTextBox 似乎不是常规文本框。一方面,它不公开句柄(这是通过 Win API 设置占位符文本所需要的)。

那么,如何在 ToolStripTextBox 上设置占位符文本或获取其 .Handle 属性?

自己没试过。

但是 Remarks 部分表明您可以直接操作 TextBox 控件。

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.

ToolStripTextBox 主持 ToolStripTextBoxControl inside which is derived from TextBox and you can access the the hosted control using its TextBox or its Control 属性。所以你可以写这样的代码:

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);
    }
}