开发者

User can press and hold only one keyboard button at a time

开发者 https://www.devze.com 2023-01-14 21:58 出处:网络
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

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 开发者_Go百科2008


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

}


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

精彩评论

暂无评论...
验证码 换一张
取 消