Search code examples
c#winformsbuttonfocus

C# Stop Button From Gaining Focus on Click


I have several buttons that when clicked I don't want them to get focus nor do I want the space bar to 'press' them again.

I want the same functionality as the buttons in windows calculator.

Googled and searched stack everything seems to be about forms eg. Make a form not focusable in C#

I know I'm supposed to rewrite WndProc but not exactly sure how to proceed as to what messages I should catch/ignore etc. As far as I got:

protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
    }

Solution

  • All you got to do is add this line to the end of the key's Click event:

    this.Focus();
    

    This line will cause the button to lose focus, the form will gain focus and spacebar will have no effect, thus satisfying your 2 conditions.

    Now if you don't want the button to be able to be clicked again, then add these 2 lines instead:

    this.Focus();
    ((Button)sender).Enabled = false;
    

    This will do what the other line did and in addition, it will disable the button.