Combobox DropDownList默认提示文本

时间:2012-01-05 12:27:54

标签: winforms drop-down-menu

所以它与Default text in combobox的问题基本相同,但对于旧的Windows窗体项目。

如何在winforms下拉列表中设置提示文字?

1 个答案:

答案 0 :(得分:1)

有一个实现,它使用PInvoke在http://www.aaronlerch.com/blog/2007/12/01/watermarked-edit-controls/

设置'cue'文本

然而,作者注意到......

  

这仅适用于Windows XP及更高版本,且仅在视觉上有效   样式已启用

... docs for CB_SETCUEBANNER表示最小客户端是Windows Vista。所以它可能不适合所有环境。

以防万一页面消失,这是相关的课程:

CueComboBox.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Lerch.Samples
{
    public class CueComboBox : ComboBox
    {
        #region PInvoke Helpers

        private static uint CB_SETCUEBANNER = 0x1703;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        private static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, String lParam);

        #endregion PInvoke Helpers

        #region CueText

        private string _cueText = String.Empty;

        /// <summary>
        /// Gets or sets the text the <see cref="ComboBox"/> will display as a cue to the user.
        /// </summary>
        [Description("The text value to be displayed as a cue to the user.")]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string CueText
        {
            get { return _cueText; }
            set
            {
                if (value == null)
                {
                    value = String.Empty;
                }

                if (!_cueText.Equals(value, StringComparison.CurrentCulture))
                {
                    _cueText = value;
                    UpdateCue();
                    OnCueTextChanged(EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// Occurs when the <see cref="CueText"/> property value changes.
        /// </summary>
        public event EventHandler CueTextChanged;

        [EditorBrowsable(EditorBrowsableState.Advanced)]
        protected virtual void OnCueTextChanged(EventArgs e)
        {
            EventHandler handler = CueTextChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        #endregion CueText

        #region Overrides

        protected override void OnHandleCreated(EventArgs e)
        {
            UpdateCue();

            base.OnHandleCreated(e);
        }

        #endregion Overrides

        private void UpdateCue()
        {
            // If the handle isn't yet created, 
            // this will be called when it is created
            if (this.IsHandleCreated)
            {
                SendMessage(new HandleRef(this, this.Handle), CB_SETCUEBANNER, IntPtr.Zero, _cueText);
            }
        }
    }
}