自定义文本框事件未触发

时间:2014-09-10 10:20:21

标签: c# winforms events

我有一个自定义TextBox用于边框属性,但OnKeyDown事件未被触发 就像原始文本框一样。

public class BorderedTextBox : UserControl
{
    System.Windows.Forms.TextBox textBox;

    public BorderedTextBox()
    {
        textBox = new TextBox()
        {
            BorderStyle = BorderStyle.FixedSingle,
            Location = new Point(-1, -1),
            Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                     AnchorStyles.Left | AnchorStyles.Right
        };

        Control container = new ContainerControl()
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(-1)
        };
        container.Controls.Add(textBox);
        this.Controls.Add(container);


        Padding = new Padding(1);
        Size = textBox.Size;
    }


    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }

    public CharacterCasing CharacterCasing
    {
        get { return textBox.CharacterCasing; }
        set { textBox.CharacterCasing = value; }
    }

    protected override void  OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
    }

    protected override void SetBoundsCore(int x, int y,
        int width, int height, BoundsSpecified specified)
    {
        base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
    }
}

1 个答案:

答案 0 :(得分:2)

不,它不会被解雇。因为焦点将在TextBox。将触发KeyDown文本框事件。

如果你需要处理这些事件,你几乎没有选择

  • BorderedTextBox而不是TextBox继承UserControl
  • 订阅textBox.KeyDown活动并处理。