Winform Enter键实现Tab键聚焦

关于tabIndex的官方文章:

https://docs.microsoft.com/zh-cn/dotnet/desktop/winforms/controls/how-to-set-the-tab-order-on-windows-forms?view=netframeworkdesktop-4.8

在一个容器里,使用Tab键会自动根据TabIndex大小顺序聚焦下一个可以聚焦的控件。(不可以聚焦控件包括:不可见、禁用、TabStop为False)

如果一个该容器的控件已经聚焦完,继续按Tab键,则会自动跳转到下一个容器(按照容器的TabIndex顺序)的控件聚焦。

 

Enter键实现Tab键一样的效果,有两种方法:窗体的SelectNextControl方法、发送Tab命令。

注意不应该使用控件的Enter事件来去实现,这个Enter命名有点迷惑性,因为通过鼠标点击、以及自动聚焦都会触发Enter事件。

using System;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 不可取的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_Enter(object sender, EventArgs e)
        {
           // SendKeys.Send("{Tab}");            
        }

        private void textBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Control ctl;
                ctl = (Control)sender;
                this.SelectNextControl(ctl, true, true, true, true);              
            }
        }

        private void textBox_KeyPress1(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SendKeys.Send("{Tab}");
                e.Handled = false;
            }
        }
    }   
}

 

posted @ 2021-06-22 15:35  舒碧  阅读(612)  评论(0编辑  收藏  举报