简体   繁体   中英

custom textbox event not fired

I have a custom TextBox for border property purposes, but the OnKeyDown event is not fired like original textbox does.

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);
    }
}

No, it will not be fired. Because the focus will be in TextBox . KeyDown event of textbox will be fired instead.

If you need to handle those events you have few options

  • Inherit the BorderedTextBox from TextBox rather than UserControl .
  • Subscribe to textBox.KeyDown event and handle it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM