4

ComboBox我们有一个 WinForms 控件,它是在没有选择或文本时支持“提示横幅”(又名水印)的扩展版本。我们的控制类似于使用 CB_SETCUEBANNER 的实现

但是,当我们将DropDownStyle控件设置为ComboBoxStyle.DropDown(即也允许自由文本输入)时,提示横幅会显示,而不是斜体(通常是这样显示的)。

有谁知道如何在ComboBoxStyle.DropDown模式下为组合框绘制斜体提示横幅???

4

2 回答 2

7

按设计。当 Style = DropDown 时,组合框的文本部分是一个 TextBox。它以非斜体样式显示提示横幅。您可以使用此代码进行验证。当 Style = DropDownList 时,区分横幅和实际选择可见是很重要的,这无疑是他们选择将其显示为斜体的原因。TextBox 的做法不同,它在获得焦点时隐藏横幅。

抛出一个非精疲力尽的版本:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CueComboBox : ComboBox {
    private string mCue;
    public string Cue {
        get { return mCue; }
        set {
            mCue = value;
            updateCue();
        }
    }
    private void updateCue() {
        if (this.IsHandleCreated && mCue != null) {
            SendMessage(this.Handle, 0x1703, (IntPtr)0, mCue);
        }
    }
    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        updateCue();
    }
    // P/Invoke
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, string lp);
}
于 2012-01-18T01:53:11.343 回答
0

C# WinForms 的更简单版本:

using System;
using System.Runtime.InteropServices; //Reference for Cue Banner
using System.Windows.Forms;

namespace Your_Project
{
    public partial class Form1 : Form
    {
        private const int TB_SETCUEBANNER = 0x1501; //Textbox Integer
        private const int CB_SETCUEBANNER = 0x1703; //Combobox Integer
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SendMessage(IntPtr hWnd, int msg,
            int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam); //Main Import for Cue Banner

        public Form1()
        {
            InitializeComponent();
            SendMessage(textBox1.Handle, TB_SETCUEBANNER, 0, "Type Here..."); //Cue Banner for textBox1
            SendMessage(comboBox1.Handle, CB_SETCUEBANNER, 0, "Type Here..."); //Cue Banner for comboBox1
        }
    }
}

之后,您可以轻松地将属性文本设置为斜体,并在用户单击或键入时更改它。

例如:

public Form1()
{
    InitializeComponent();
    textBox1.Font = new Font(textBox1.Font, FontStyle.Italic); //Italic Font for textBox1
    comboBox1.Font = new Font(comboBox1.Font, FontStyle.Italic); //Italic Font for comboBox1
    SendMessage(textBox1.Handle, TB_SETCUEBANNER, 0, "Type Here..."); //Cue Banner for textBox1
    SendMessage(comboBox1.Handle, CB_SETCUEBANNER, 0, "Type Here..."); //Cue Banner for comboBox1
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.Text != "")
    {
        textBox1.Font = new Font(textBox1.Font, FontStyle.Regular); //Regular Font for textBox1 when user types
    }
    else
    {
        textBox1.Font = new Font(textBox1.Font, FontStyle.Italic); //Italic Font for textBox1 when theres no text
    }
}
于 2017-03-27T07:50:29.797 回答