sharing about .NET and technology RSS 2.0
# Thursday, February 22, 2007

In many enterprise applications there is the need that, regardless on which control you have the focus, that you can hit the 'Enter' and/or 'Esc' key to perform a default action. This behaviour is also common to web applications. On the Form control you find properties like AcceptButton and CancelButton, whereas the UserControl doesn't have these properties. The code below contains an AcceptButton and CancelButton that allows you to define a default action when the Enter or Esc key is pressed respesctively.

public class UserControlEx : System.Windows.Forms.UserControl
{    
    private Button _acceptButton;
    private Button _cancelButton;

    public event EventHandler<EventArgs> AcceptEvent;
    public event EventHandler<EventArgs> CancelEvent;

    [Browsable(true)]
    public Button AcceptButton
    {
        get { return _acceptButton; }
        set { _acceptButton = value; }
    }

    [Browsable(true)]
    public Button CancelButton
    {
        get { return _cancelButton; }
        set { _cancelButton = value; }
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (msg.WParam.ToInt32() == (int)Keys.Enter)
        {
            OnAcceptEvent(EventArgs.Empty);

            if (_acceptButton != null)
                _acceptButton.PerformClick();
        }

        if (msg.WParam.ToInt32() == (int)Keys.Escape)
        {
            OnCancelEvent(EventArgs.Empty);

            if (_cancelButton != null)
                _cancelButton.PerformClick();
        }

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

    protected virtual void OnAcceptEvent(EventArgs args)
    {
        if (AcceptEvent != null)
            AcceptEvent(this, args);
    }

    protected virtual void OnCancelEvent(EventArgs args)
    {
        if (CancelEvent != null)
            CancelEvent(this, args);
    }
}
Thursday, February 22, 2007 10:32:31 PM (Romance Standard Time, UTC+01:00) -  # -  Comments [3] -
.NET | Windows Forms
Navigation
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Christoph De Baene
Sign In
Statistics
Total Posts: 176
This Year: 2
This Month: 0
This Week: 0
Comments: 283
All Content © 2010, Christoph De Baene
DasBlog theme 'Business' created by Christoph De Baene