C# Stop Button From Gaining Focus on Click

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-17 20:16:00

问题


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

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6741544/c-sharp-stop-button-from-gaining-focus-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!