Disadvantage of setting Form.KeyPreview = true?

后端 未结 4 881
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 10:59

I wonder what the Form.KeyPreview property actually is good for? Why do it exist and what do I \"risk\" by setting it to true? I guess it must have some negative ef

4条回答
  •  盖世英雄少女心
    2020-12-01 11:29

    A simple and trivial, though practical reason:

    In a game like Space Invaders https://www.mooict.com/c-tutorial-create-a-full-space-invaders-game-using-visual-studio/ the user repeatedly hammers the space bar to vaporize aliens. When the last invader is gone, a text box pops up to say, "good job". The user's still twitching thumb hits the space bar (or maybe just the keyboard buffer releases?) and the congrats MessageBox vanishes before it can be read. I couldn't see a work around because of how Forms handle button/space bar clicks.

    My custom dialog uses keypreview to preprocess keystrokes sent to the GameOverDialog to ignore any space bar taps. The user has to close with a mouse click or Enter. This is a just a FixedDialog with a "you win" label and an [OK] button.

    public partial class GameOverDialog : Form
    {
        public GameOverDialog()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.MinimizeBox = false;
        }
    
        // keyhandler keypreview = true
        private void SpaceDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                e.Handled = true;
                return;
            }
        }
    
        private void SpaceUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                e.Handled = true;
                return;
            }
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
    

    Also, an interesting option that I've not tested: If you think about it, this would be a great way to embed cheats, hidden messages, etc. into innocuous [OK] dialogs or any Form that allows key preview.

提交回复
热议问题