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

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

最佳答案

ToolStripTextBox承载一个内部ToolStripTextBoxControl,该内部派生自TextBox,您可以使用其TextBoxControl属性访问托管控件。因此,您可以编写以下代码:

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

10-06 00:36