0

嗨,我知道我的代码哪里出错了,但不知道如何解决它...

在 TextChanged 事件中,我调用了我的验证函数,它执行(应该执行)以下操作:

  • 删除任何非字母字符
  • 将输入的字母转换为大写
  • 文本框中只允许一个字符
  • 使用 SendKeys 增加标签索引(转到下一个文本框)

问题是因为它在 textchanged 事件中,我试图与它作斗争以防止它两次跳动(它正在这样做)。因为如果我单步执行,输入的首字母是第一个 textchanged 事件,那么如果它是一个不允许的字符,则再次调用该函数,但如果它是一个字母,则 ToUpper 可能会再次更改它,因此选项卡被发送两次. 有任何想法吗?我知道有一种方法可以在不设置一些复杂布尔值的情况下做到这一点......

private void validateTextInteger(object sender, EventArgs e)
        {
            TextBox T = (TextBox)sender;
            try
            {
                //Not Allowing Numbers, Underscore or Hash
                char[] UnallowedCharacters = { '0', '1','2', '3', '4', '5','6', '7','8', '9','_','#','%','$','@','!','&',
                                           '(',')','{','}','[',']',':','<','>','?','/','=','-','+','\\','|','`','~',';'};

                if (textContainsUnallowedCharacter(T.Text, UnallowedCharacters))
                {
                    int CursorIndex = T.SelectionStart - 1;
                    T.Text = T.Text.Remove(CursorIndex, 1);
                    //Align Cursor to same index
                    T.SelectionStart = CursorIndex;
                    T.SelectionLength = 0;
                }
            }
            catch (Exception) { }
            T.Text = T.Text.ToUpper();
            if (T.Text.Length > 0)
            {
                 //how do i prevent this (or this function) from getting called twice???
                 SendKeys.Send("{TAB}");
            }
        }
4

1 回答 1

1

无需使用 SendKeys 来模拟 TAB 按键,您可以在 Tab 键顺序中找到下一个可见控件并对其调用 Focus。像这样的东西:

private void FocusOnNextVisibleControl(Control currentControl)
{
    Form form = currentControl.FindForm();
    Control nextControl = form.GetNextControl(currentControl, true);
    while (nextControl != null && !nextControl.Visible && nextControl != currentControl)
    {
        nextControl = form.GetNextControl(nextControl, true);
    }
    if (nextControl != null && nextControl.Visible)
    {
        nextControl.Focus();
    }
}

要调用此方法,请替换SendKeys.Send("{TAB}");FocusOnNextVisibleControl(T);

于 2012-02-07T05:48:32.423 回答