简体   繁体   中英

How to enable a WinForm button in time to receive focus by tabbing

Visual Studio 2010, C#

I have a ComboBox with a DropDown , AutoComplete set to SuggestAppend and the AutoCompleteSource is from the ListItems . The user keys data into it until the have the correct entry. Utill the data matches one of the list items, a button next to the combobox is disabled.

If the user hits the tab key the autocomplete feature accepts current suggestion. It also moves on to the next control in tab sequence that is enabled. Of course since I want it to go to the disbabled button I need to enable it as soon as I validate the entry.

The problem is that none of the events I've tried, PreviewKeyDown , LostFocus , SelectedIndexChanged allow me to enable the button in time for it to be proccessed and receive the focus. It always goes to the next button in tab order which is always enabled.

I am about ready to leave the button enabled and have it give an error if pressed too soon but I don't want to do it that way. I also don't want to get into have special mode flags to keep track of when these controls receive focus. Validation seems to be a normal thing, but I'm stuck.

If the SelectedIndexChanged worked when the user made a match this would be easy. It doesn't fire when the box clears nor when a typed match is found.

You could create your own ComboBox class to encapsulate this behavior. Something like this:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.myComboBox1.TheButton = this.button1;

            this.myComboBox1.Items.AddRange( new string[] {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            } );

            button1.Enabled = false;
        }
    }

    public class MyComboBox : ComboBox
    {
        public Control TheButton { get; set; }

        public MyComboBox()
        {
        }

        bool IsValidItemSelected
        {
            get { return null != this.SelectedItem; }
        }

        protected override void OnValidated( EventArgs e )
        {
            if ( null != TheButton )
            {
                TheButton.Enabled = this.IsValidItemSelected;
                TheButton.Focus();
            }

            base.OnValidated( e );
        }

        protected override void OnTextChanged( EventArgs e )
        {
            if ( null != TheButton )
            {
                TheButton.Enabled = this.IsValidItemSelected;
            }

            base.OnTextChanged( e );
        }
    }
}
try this :

key_press event :

if (e.KeyData == Keys.Enter)
        {
            button2.Enabled = true;
            button2.Focus();
        }

Instead of the event hanlders you mentioned, (LostFocus, SelectedIndexChanged and PreviewKeyDown) use the "Validated" event of your combobox to set the enabled state of the button.

You may need to also manually focus on the button to force the focus to move to it though.

eg

    private void comboBox1_Validated(object sender, EventArgs e)
    {
        button1.Enabled = true;
        button1.Focus();
    }

With some thought to the other answers here I came up with a partial senario that works without using AutoComplete . A side effect is that the PreviewKeyDown event is called a second time and therefore validation is called twice. I wonder why... maybe I should ask another question.

    private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
      if (e.KeyData == Keys.Tab) {
        if (ValidationRoutine()) {
          e.IsInputKey = true;  //If Validated, signals KeyDown to examine this key
        } //Side effect - This event is called twice when IsInputKey is set to true
      }          
    }

    private void comboBox1_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyData == Keys.Tab) {
          e.SuppressKeyPress = true; //Stops further processing of the TAB key
          btnEdit.Enabled = true;
          btnEdit.Focus();
      }
    }

Once you turn on AutoCompleteMode with any setting other than None , the KeyDown event doesn't fire for Tab anymore the key is silently eaten.

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