当DropDownStyle是DropDown时,ComboBox Cue Banner不是斜体

我们有一个WinForms控件,它是ComboBox的扩展版本,当没有选择或文本时,它支持“cue banners”(也就是水印)。 我们的控制与使用CB_SETCUEBANNER的此实现类似。

但是,当我们将DropDownStyle设置为ComboBoxStyle.DropDown (也就是说,也允许自由文本输入)时,cue横幅显示,而不是斜体(通常显示的方式)。

有没有人知道如何在斜体中为ComboBoxStyle.DropDown模式中的combobox绘制提示横幅?

按设计。 当Style = DropDown时,combobox的文本部分是TextBox。 以非斜体样式显示提示横幅。 您可以使用此代码进行validation。 当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); } 

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