简体   繁体   中英

C# ComboBox disable highlighting

I have custom ComboBox, where DropDownStyle = ComboBoxStyle.DropDown; .DropDown style is set because I want to set the Text property of the ComboBox to something outside the list of values. Everything works good, except that ComboBox is highlighting the text when it's left and when I click on the combobox editing is avaible. How can I cope with this? To illustrate:

在此处输入图片说明

First Picture is where everything looks good, second is the highlight situation, third editing is on.

Try un-selecting the text after the DropDown closes:

void comboBox1_DropDownClosed(object sender, EventArgs e) {
  this.BeginInvoke(new Action(() => { comboBox1.Select(0, 0); }));
}

Tricky problem to solve. It seems to be from the Resize event. There are a lot of solutions that do something similar to this, but none that I've seen worked for me until I tried this. (This is a solution that does not require inheritance from ComboBox ; inheriting is probably a much more straight forward solution, but requires you to always use your inherited class and never the actual ComboBox class.)

comboBox.Resize += (s, e) => {
   if (!comboBox.IsHandleCreated)
      return;  // avoid possible exception

   comboBox.BeginInvoke(new Action(() => comboBox.SelectionLength = 0));
};

Set the selection length to zero to get rid of the highlight, but when? Other examples do it in other places, but the problem seems to be specifically caused by Resize , so doing it after Resize fixes it consistently, at least for me. (Can still see it flicker when you resize the window though, but it always ends up ok.)

BeginInvoke ensures that it happens sufficiently after Resize to work, and the check for IsHandleCreated prevents it from being called before the handle is created, in which case BeginInvoke would throw an exception.

This slightly more complex version includes some checks to prevent a focused control from losing highlight, since it actually should have it. It also doesn't fire if the parent doesn't exist yet, or if the parent does not have an active control yet, both signs that things are too early.

comboBox.Resize += (s, e) => {
   if (!comboBox.IsHandleCreated)
      return;

   comboBox.BeginInvoke(new Action(() => {
      var parent = comboBox.FindForm();
      if (parent == null)
         return;

      if (parent.ActiveControl == null)
         return;

      if (parent.ActiveControl == comboBox)
         return;

      comboBox.SelectionLength = 0;
   }));
};

I tried to make a version that would 'preserve' the selection length rather than always set it to zero, but I couldn't get it to synchronize properly. Many Resize events can fire before the BeginInvoke delegates start to fire, so the preserved value will always be overwritten by the broken one. I tried saving them all in a Queue or Stack , but in both cases, I was unable to reverse the ordering (not really sure why, since that makes no sense).

如果您指的是禁用突出显示和编辑,那么您可能需要考虑将DropdownStyle属性设置为DropdownList

yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

To solve the same I have tried almost EVERYTHING:

  • setting the DropdownStyle property to DropdownList
  • this.BeginInvoke(new Action(() => { comboBox1.Select(0, 0); }));
  • combobox1.SelectionLength = 0;
  • changing comboBox.TabIndex
  • Not tried SendKeys.Send("{ESC}"); because it is not a reliable solution

Nothing helped. The only stable and working solution was to move a focus on another Label control:

    label.Focus();

You could also hide that label.

I know this post is old but recently I have the same problem with combobox.

Situation : I have an editable combobox which propose complete words when user write some letters.

But when I want to type a letter, combobox auto highlight the text and the next letter auto replace the previous.

Solution : I use a textbox to avoid any highlight like that:

<ComboBox IsTextSearchEnabled="False" IsEditable="True" x:Name="CMB_ClientName"/>
<TextBox Text="{Binding ElementName=CMB_ClientName, Path=Text}" TextChanged="ComboBoxChange" x:Name="TXT_ClientName"/>

And I generate the textbox TextChanged event :

private void ComboBoxChange(object sender, TextChangedEventArgs e)
    {
        //Clear ComboBox items
        CMB_ClientName.Items.Clear();
        //Auto Open DropDownList
        CMB_ClientName.IsDropDownOpen = true;

        //Get data from database (use entity framework 6.x)
        dbEntity.Client.Load();

        //Attribute Data to variable
        var clients = dbEntity.Client.Local;


        foreach (Client client in clients)
        {
            //If data begin with the texbox text, the data is add to the combobox items list.
            if (client.Nom.ToLower().StartsWith(TXT_NomClient.Text.ToLower()))
            {
                CMB_ClientName.Items.Add(client.Nom);
            }
        }
    }

I know this solution isn't realy beautifull, but it is for me the easiest solution to avoid highlight text and all the solutions in this post don't work for me.

I hope this solution will be helpfull, thanks for reading.

Math.

Ps: My apologies, my English is not very good. I hope you will understand me correctly.

Nothing worked for me ( I want the form to load with no highlighting in any combobox) until I set the combobox property TabStop to false. This meant that one of my buttons took the tab highlight which I didn't like so I set them all to false for start up and adjusted them programatically as needed.

I know this is an old thread, but my solution is similar to that of the others, but relies on the Form.ResizeEnd event. In its event handler, I iterate through the ComboBoxes and set ComboBox.SelectionLength to 0.

private void Form_ResizeEnd(object sender, EventArgs e)
{
    foreach(ComboBox comboBox in parentControl.Controls.OfType<ComboBox>
    {
        comboBox.SelectionLength = 0;
    }
}

This is what worked for me:

  1. Set DrawMode to OwnerDrawFixed

  2. Set cbxSubsystems.DrawItem event to the function below

private void cbxSubsystems_DrawItem(object sender, DrawItemEventArgs e)
{
    Color BgClr;
    Color TxClr;

    if( (e.State & DrawItemState.ComboBoxEdit) == DrawItemState.ComboBoxEdit )
    {
        // Do not highlight main display
        BgClr = cbxSubsystems.BackColor;
        TxClr = cbxSubsystems.ForeColor;
    }
    else
    {
        BgClr = e.BackColor;
        TxClr = e.ForeColor;
    }

    e.Graphics.FillRectangle(new SolidBrush(BgClr), e.Bounds);

    TextRenderer.DrawText(e.Graphics, cbxSubsystems.Items[e.Index].ToString(), e.Font, e.Bounds,
        TxClr, BgClr, TextFormatFlags.Left | TextFormatFlags.VerticalCenter );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM