Having some fun - what is a good way to include a secret key functionality and fire the KeyDown event?

Posted by Sisyphus on Stack Overflow See other posts from Stack Overflow or by Sisyphus
Published on 2012-07-09T08:44:47Z Indexed on 2012/07/09 9:15 UTC
Read the original article Hit count: 257

Filed under:
|
|

To keep myself interested, I try to put little Easter Eggs in my projects (mostly to amuse myself). I've seen some websites where you can type a series of letters "aswzaswz" and you get a "secret function" - how would I achieve this in C#?

I've assigned a "secret function" in the past by using modifier keys

        bool showFunThing = (Control.ModifierKeys & Keys.Control) == Keys.Control;

but wanted to get a bit more secretive (without the modifier keys) I just wanted the form to detect a certain word typed without any input ... I've built a method that I think should do it:

    private StringBuilder _pressedKeys = new StringBuilder();

    protected override void OnKeyDown(KeyEventArgs e)
    {
        const string kWord = "fun";
        char letter = (char)e.KeyValue;
        if (!char.IsLetterOrDigit(letter))
        { return; }
        _pressedKeys.Append(letter);
        if (_pressedKeys.Length == kWord.Length)
        {
            if (_pressedKeys.ToString().ToLower() == kWord)
            {
                MessageBox.Show("Fun");
                _pressedKeys.Clear();
            }
        }
        base.OnKeyDown(e);
    }

Now I need to wire it up but I can't figure out how I'm supposed to raise the event in the form designer ... I've tried this:

    this.KeyDown +=new System.Windows.Forms.KeyEventHandler(OnKeyDown);

and a couple of variations on this but I'm missing something because it won't fire (or compile). It tells me that the OnKeyDown method is expecting a certain signature but I've got other methods like this where I haven't specified arguments.

I fear that I may have got myself confused so I am turning to SO for help ... anyone?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET