如何通过Tab键及时启用WinForm按钮以获得焦点
Visual Studio 2010,C#
我有一个带DropDown
的ComboBox
, AutoComplete
设置为SuggestAppend
, AutoCompleteSource
来自ListItems
。 用户将数据键入其中,直到具有正确的条目。 如果数据与列表项之一匹配,则combobox旁边的按钮被禁用。
如果用户点击Tab键,则自动完成function会接受当前建议。 它还会移动到启用的选项卡序列中的下一个控件。 当然,因为我希望它转到disbabled按钮,我需要在validation条目后立即启用它。
问题是我没有尝试过任何事件, PreviewKeyDown
, LostFocus
, SelectedIndexChanged
允许我及时启用按钮以使其被处理并获得焦点。 它始终以Tab键顺序进入下一个按钮,该按钮始终处于启用状态。
我准备好让按钮保持启用状态,如果太快按下它就会出错,但我不想这样做。 我也不想进入特殊模式标志来跟踪这些控件何时获得焦点。 validation似乎是正常的事情,但我被困住了。
如果SelectedIndexChanged
在用户进行匹配时起作用,则这很容易。 当盒子清除时,或者当找到类型匹配时,它不会触发。
您可以创建自己的ComboBox类来封装此行为。 像这样的东西:
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事件:
if (e.KeyData == Keys.Enter) { button2.Enabled = true; button2.Focus(); }
而不是你提到的事件hanlders,(LostFocus,SelectedIndexChanged和PreviewKeyDown)使用combobox的“Validated”事件来设置按钮的启用状态。
您可能还需要手动对焦按钮以强制焦点移动到它。
例如
private void comboBox1_Validated(object sender, EventArgs e) { button1.Enabled = true; button1.Focus(); }
考虑到其他答案,我想出了一个不使用AutoComplete的部分Senario。 副作用是第二次调用PreviewKeyDown事件,因此调用两次validation。 我想知道为什么……也许我应该问另一个问题。
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(); } }
一旦使用除None
之外的任何设置打开AutoCompleteMode
, KeyDown
事件就不再为Tab
激活,密钥被静默吃掉。