How to add placeholder text to ToolStripTextBox?

╄→гoц情女王★ 提交于 2019-12-24 00:33:29

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/50918225/how-to-add-placeholder-text-to-toolstriptextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!