简体   繁体   English

C# 如何在文本框为空时防止按 Tab 键

[英]C# how do I prevent tab key press when textbox is empty

Below code is work fine but how can I stop tab key when my textbox.text is empty how I put my if logic in ProcessCmdKey event?下面的代码工作正常,但是当我的 textbox.text 为空时如何停止 Tab 键,我如何将 if 逻辑放在 ProcessCmdKey 事件中?

bool a = true;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Tab && !a)
    {
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

Override ProcessTabKey() and return true if you want to suppress Tab movement.如果要抑制 Tab 移动,请覆盖ProcessTabKey()并返回 true。 You could check this.ActiveControl if you want it to work only for TextBoxes.如果您希望它仅适用于文本框,您可以检查this.ActiveControl

Here's a version that only suppresses Tab for those TextBoxes listed in the "SelectTextBoxes" List:这是一个仅抑制“SelectTextBoxes”列表中列出的文本框的 Tab 的版本:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        SelectTextBoxes = new List<TextBox>() { textBox1, textBox2, textBox3 }; // list the textboxes here
    }

    private List<TextBox> SelectTextBoxes = new List<TextBox>(); 

    protected override bool ProcessTabKey(bool forward)
    {
        Control ctl = this.ActiveControl;
        if (ctl != null && ctl is TextBox)
        {
            TextBox tb = (TextBox)ctl;
            if (SelectTextBoxes.Contains(tb) && tb.Text.Length == 0)
            {
                return true;
            }
        }
        return base.ProcessTabKey(forward); // process TAB key as normal
    }

}

Modify the code to the following:修改代码如下:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Tab && string.IsNullOrEmpty(textbox.Text))
        return true;

    return base.ProcessCmdKey(ref msg, keyData);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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