Set hint or watermark or default text for ComboBox without adding it as item

前端 未结 3 1631
离开以前
离开以前 2020-12-04 03:46

So, I\'m trying to put some text showing up on the ComboBox before it has a selection made by the user.

That text should not be an item, selectable by t

3条回答
  •  情书的邮戳
    2020-12-04 04:04

    Hint, Cue Banner, Watermark or Default Text for ComboBox

    You can set hint for ComboBox without adding to items. To do so, if the ComboBox has DropDown or Simple mode, you can send a CB_SETCUEBANNER message to its inner edit control to set hint. If the combo has DropDownListMode, you can handle WM_PAINT or set it to owner draw to draw hint:

    ComboBox Select Text without adding Item ComboBox Select Text without adding Item

    Download

    You can clone or download the working example:

    • Download zip
    • GitHub repository

    Code

    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    public class MyComboBox : ComboBox
    {
        public MyComboBox()
        {
            DrawMode = DrawMode.OwnerDrawFixed;
        }
        const int CB_SETCUEBANNER = 0x1703;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SendMessage(IntPtr hWnd, int msg, int wParam, string lParam);
        string hint;
        public string Hint
        {
            get { return hint; }
            set { hint = value; UpdateHint(); }
        }
        private void UpdateHint()
        {
            if (!this.IsHandleCreated)
                return;
            if (DropDownStyle == ComboBoxStyle.DropDownList)
                this.Invalidate();
            else
                SendMessage(Handle, CB_SETCUEBANNER, 0, Hint);
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            if (!string.IsNullOrEmpty(Hint))
                UpdateHint();
        }
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            string text = Hint;
            base.OnDrawItem(e);
            if (e.Index > -1)
                text = this.GetItemText(this.Items[e.Index]);
            e.DrawBackground();
            TextRenderer.DrawText(e.Graphics, text, Font,
                e.Bounds, e.ForeColor, TextFormatFlags.TextBoxControl);
        }
    }
    

提交回复
热议问题