简体   繁体   中英

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

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.

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.

As mentioned in the comments, I find the easiest way to do this is to add an input control to the form that does nothing (has no event handlers), and then in the OnClick method of the button use Control.Focus() . However, please note that this won't work if you set the dummy control's Visible property to false.

So my solution was to add a dummy button, set its size to 0, 0 and set the focus to that each time. I suppose you could also place the control behind something else or outside the bounds of a non-resizable form or panel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM