Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 269
StudentJ Avatar asked Nov 27 '22 09:11

StudentJ


1 Answers

I dealt with this problem today, and below is the answer that was easiest for me. I didn't want to use this.Focus() because I needed focus to remain unchanged.

http://social.msdn.microsoft.com/Forums/windows/en-US/f1babeac-4bd9-498f-b19b-90b9fed0d751/c-stop-button-from-gaining-focus-on-click

Create your own button class that can't be selected.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YourNameSpaceHere {
    class NoSelectButton : Button{

        public NoSelectButton() {

            SetStyle(ControlStyles.Selectable, false);

        }
    }
}

Now, go update the design file with NoSelectButton instead of the System's version. Should be in two locations per instance.

Nb: The Visual Studio designer may momentarily break its preview until you press Start.

like image 199
C4F Avatar answered Dec 11 '22 01:12

C4F