如何在文本框中使用回车键? [英] How to use enter key in textbox?

查看:108
本文介绍了如何在文本框中使用回车键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在Visual Studio 2017 / C#/ Sql Server(数据库)中创建的程序。我有几个名为firstname,middlename和lastname的文本框。在将数据输入到firstname文本框并按回车键后,如何进入midlename文本框。



我尝试过:



任何帮助将不胜感激。非常感谢。

I have a program created in Visual Studio 2017 / C# / Sql Server(Database). I have several textboxes named firstname, middlename and lastname. How can I proceed into midlename textbox after I input data into the firstname textbox and press enter.

What I have tried:

Any help would be appreciated. Thankyou so much.

推荐答案

你的项目是不是网络?如果您使用的是桌面应用,可以尝试这一点(在KeyDown事件中):

Your project is Web or not? If you're on desktop apps you can try this (inside KeyDown event):
if (e.KeyData == Keys.Enter)
{
    e.SuppressKeyPress = true;
    SelectNextControl(YOUR_CONTROL_HERE, true, true, true, true);
}



如果您的项目是网络 londhess解决方案很好。


Quote:

Dave K.写道:通过使用ENTER从一个字段移动到另一个字段,你违背了Windows应用程序的标准功能。

Dave K. wrote: "By using ENTER to move from field to field, you are going against the standard functionality of Windows applications."

我恭敬地不同意这种说法,因为我认为它过于笼统,过于绝对。 br />


在许多情况下,应用程序根据某些规则集或按顺序控制用户从控制到控制的交互焦点。 向导就是一个很好的例子。



Windows Forms的设计者只需设置即可将任何Control从 TabStop 中删除财产。对于TextBox和RichTextBox,两者都提供了对Tabs是否被接受的控制,而TextBox允许你忽略Enter。



我相信这些选项是有原因的:使开发人员能够灵活地设计应用程序行为。



现在,让我向您展示一个相当完整的草图(这意味着它适用于VS 2017),用于WinForm UserControl,通过六个TextBox顺序管理用户数据条目。这个UserControl有两个按钮,'btnSubmit和'btnCancel ..



UserControl中的所有控件都将其TabStop属性设置为'false。 TextBoxes将AcceptsTab和AcceptsReturn属性都设置为false。



UserControl上的所有键输入都被OverCratedChd截取。



验证器附加到前三个TextBox:第一个需要至少一个数字才能完成;第二个需要2位数和2个标点才能完成;第三个需要一些任何类型的文本输入。其他三个TextBox有一个默认的验证器,它接受任何东西,或者没有文本。



当用户到达最后一个TextBox时,如果没有验证错误,则提交按钮已启用。

I respectfully disagree with this statement in the sense that I think it is too generalized, too absolute.

There are many scenarios where an application controls the focus of user interaction from Control to Control according to some set of rules, or, in sequential order. A "wizard" is a good example.

The designers of Windows Forms allow any Control to be removed from being a TabStop by simply setting a property. For TextBox and RichTextBox, both offer Control over whether Tabs are accepted, and the TextBox allows you to ignore Enter.

These options, I believe, are there for a reason: to enable developers to have flexibility for designing application behavior.

Now, let me show you a fairly complete sketch (that means it works in VS 2017) for a WinForm UserControl that manages the users data entry in sequence through six TextBoxes. This UserControl has two Buttons, 'btnSubmit, and 'btnCancel..

All Controls in the UserControl have their TabStop property set to 'false. The TextBoxes have both AcceptsTab, and AcceptsReturn properties set to false.

All key-entry on the UserControl is intercepted by over-riding ProcessCmdKey.

Validators are attached to the first three TextBoxes: the first requires at least one digit to complete; the second requires 2 digits and 2 punctuations to complete; the third requires some text entry of any type. The other three TextBoxes have a default validator defined that accepts anything, or no text.

When the user reaches the last TextBox, if there is no validation error, the Submit Button is enabled.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MatrixTestForm
{
    public partial class DataEntryUserControl : UserControl
    {
        public DataEntryUserControl()
        {
            InitializeComponent();
        }

        public Action<List<string>> SendData;
        
        public Dictionary<TextBox,Func<TextBox, bool>>  TxtBxesToValidator = new Dictionary<TextBox, Func<TextBox, Boolean>>();

        private bool allValid = false;

        private List<TextBox> textBoxes = new List<TextBox>();
        private TextBox activeTextBox;
        private int lastTBoxIndex;
        
        private void DataEntryUserControl_Load(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false;
            
            textBoxes.AddRange(new List<TextBox>()
            {
                textBox1, textBox2, textBox3, textBox4, textBox5, textBox6
            });

            lastTBoxIndex = textBoxes.Count - 1; // adjust for #0 offset

            foreach (var tbx in textBoxes)
            {   
                tbx.Enter += TbxOnEnter;
                tbx.Leave += TbxOnLeave;
            }
            
            activeTextBox = textBox1;
            textBox1.Capture = true;

            // no digits
            toolTip1.SetToolTip(textBox1, "no digits");
            TxtBxesToValidator[textBox1] = box =>
            {
                return box.Text != null && !box.Text.Any(char.IsDigit);
            };

            // must have 2 digit2 and 2 punctuation
            toolTip1.SetToolTip(textBox2,"2 digits, 2 ounctuation");
            TxtBxesToValidator[textBox2] = box =>
            {
                return box.Text != null
                       && box.Text.Any(char.IsDigit)
                       && box.Text.Where(char.IsDigit).Count() == 2
                       && box.Text.Any(char.IsPunctuation)
                       && box.Text.Where(char.IsPunctuation).Count() == 2;
            };

            // gotta have something
            toolTip1.SetToolTip(textBox3, "enter something");
            TxtBxesToValidator[textBox3] = box =>
            {
                return !String.IsNullOrWhiteSpace(box.Text);
            };
        }
        
        private void TbxOnEnter(Object sender, EventArgs eventArgs)
        {
            activeTextBox = sender as TextBox;
            activeTextBox.Capture = true;
        }

        private void TbxOnLeave(Object sender, EventArgs eventArgs)
        {
            activeTextBox.Capture = false;
            activeTextBox = null;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter && activeTextBox != null)
            {
                activeTextBox.Capture = false;
                
                // validator

                if (TxtBxesToValidator.ContainsKey(activeTextBox))
                {
                    allValid = TxtBxesToValidator[activeTextBox](activeTextBox);      
                }

                if (! allValid)
                {
                    btnSubmit.Enabled = false;
                    MessageBox.Show("invalid");
                    return base.ProcessCmdKey(ref msg, keyData);
                }

                int ndx = textBoxes.IndexOf(activeTextBox);

                if (ndx == lastTBoxIndex)
                {
                    btnSubmit.Enabled = allValid;
                }
                else
                {
                    textBoxes[ndx + 1].Focus();
                    textBoxes[ndx + 1].Capture = true;
                }

                return true;
            }

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

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false;
            
            // whatever : hide the UserControl ?
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            // send the valid data back to wherever ?
            SendData?.Invoke(textBoxes.Select(tbx => tbx.Text).ToList());
            
            // clean-up
            // hide the UserControl ?
            // clear the TextBoxes ?
            // other ??
        }
    }
}


通过使用ENTER从一个字段移动到另一个字段,你违背标准功能的Windows应用程序。 ENTER被视为表单的提交按钮,而不是移动到下一个字段。



但是,可以使用 Control.SelectNextControl() [ ^ ]。



我还没有用过它,但看完文档后,我可能会自定义TextBox控件(创建一个新类并从TextBox派生)并覆盖它开始的OnKeyDown方法:

By using ENTER to move from field to field, you are going against the standard functionality of Windows applications. ENTER is considered as the Submit button for a form, not move to the next field.

But, it is possible with Control.SelectNextControl()[^].

I haven't used it but after looking at the documentation, I would probably make a custom TextBox control (create a new class and derive from TextBox) and override its OnKeyDown method for a start:
private override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;

        Parent.SelectNextControl(this, true, true, true, true);
    }
    else
    {
        base.OnKeyDown(e);
    }
}



警告!!

为了实现这一点,父表格不能拥有它的AcceptButton属性集。它必须是(无)。


WARNING!!
In order for this to work, the parent Form can NOT have it's AcceptButton property set. It must be "(none)".


这篇关于如何在文本框中使用回车键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆