tags:

views:

46

answers:

2

Hi there,

I have a standard WinForms-application. I want to implement such functionality:

user can press and hold only one keyboard button at a time. If he tried to press a button, while another button pressed, then it gets no result.

PS: this behavior spreads only to a form that I want, not to all forms of my application.

C#, 2.0 - 3.5, VS 2008

A: 

I banged this out pretty quickly, so you might have to tinker with it to make it work, but it should get you started.

Set your form's KeyPreview to true. Put the in a KeyDown event and KeyUp Event.

   Keys MyKey;
        bool KeyIsDown = false;
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (KeyIsDown)
            {
                e.Handled = true;
            }
            else
            {
                MyKey = e.KeyData;
            }
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (KeyIsDown)
            {
                if (e.KeyData == MyKey)
                {
                    KeyIsDown = false;
                }
            }
        }
Khadaji
+1  A: 

I got something similar than Khadaji

    private Keys CurrentKey = Keys.None;

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (CurrentKey == Keys.None)
        {
            CurrentKey = e.KeyData;
            // TODO: put your key trigger here
        }
        else
        {
            e.SuppressKeyPress = true;
        }

    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyData == CurrentKey)
        {
            // TODO: put you key end trigger here
            CurrentKey = Keys.None;
        }
        else
        {
            e.SuppressKeyPress = true;
        }

    }
Hapkido
The addtion of CurrentKey = Keys.None is a good one. I wasn't sure what the exact syntax was and was in too big a hurry this morning to look it up.
Khadaji