本文介绍了如何创建继承自 TextBox 的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个继承TextBox的自定义TextBox类并覆盖 onKeyDown 事件以在按下 Enter 键时启用 Tab 功能.

I want to make a custom TextBox class that inherits TextBoxand overrides onKeyDown event to make Tab functionality when key Enter is pressed.

这个问题有重复,但我找到的答案都没有意义,所以我想开始新的讨论.

There is duplicates of this question but none of the answers I found make sense so I want to open a fresh discussion.

我不想从 UserControl 而是从 TextBox 继承...这真的很难吗?我似乎无法找到有关如何执行此操作的直接教程或示例.

I don't want to Inherit from UserControl but from TextBox... is this really that hard to do? I can't seem to find straightfoward tutorial or example on how to do this.

像这样:

public partial class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        this.KeyDown += customKeyDown;
    }

    void customKeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            SendKeys.Send("{TAB}");
        }
    }
}

请记住,我在使用 UserControls 或 CustomControls 方面的经验很少,而且是很久以前的事了,所以我忘记了关键的事情

Please keep in mind that I have very little experience with working with UserControls or CustomControls and it was long time ago so I forgot the key things

推荐答案

您只需覆盖 OnKeyDown 事件处理程序,此处无需 UserControl.

You just override OnKeyDown event handler, no need for UserControl here.

当在单行或多行文本框中按下 ENTER 键时,下面的类将移动到下一个控件.多行时,可以通过按 SHIFT+ENTER 插入 ENTER.

Class below moves to next control when ENTER key is pressed in single- or multiline textbox. When multiline, ENTER can be inserted by pressing SHIFT+ENTER.

作为额外的奖励,烦人的叮"声被抑制了(以最简单的方式,如果您不需要处理控制范围外的按键,效果会很好).

As added bonus, annoying "ding" sound is suppressed (in simplest possible way which works well if you do not need to handle the key outside the control).

namespace YourNameSpace
{
    public class CustomTextBox : TextBox
    {
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (e.KeyCode == Keys.Enter && (!Multiline || Multiline && !e.Shift))
            {
                SendKeys.Send("{TAB}");
                // Removes "ding" sound by NOT passing the key down to container
                e.SuppressKeyPress = true;
            }
        }
    }
}

这篇关于如何创建继承自 TextBox 的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:22
查看更多