C#停止按钮从获得焦点点击

Stu*_*ntJ 4 c# forms windows focus button

我有几个按钮,点击时我不希望它们得到焦点,我也不希望空格键再次"按下"它们.

我想要与Windows计算器中的按钮相同的功能.

谷歌搜索和搜索堆栈一切似乎是关于形式,例如.使表单无法在C#中聚焦

我知道我应该重写WndProc但不完全确定如何处理我应该捕获/忽略的消息等等.据我所知:

protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
    }
Run Code Online (Sandbox Code Playgroud)

RW4*_*RW4 17

我今天处理了这个问题,下面是对我来说最简单的答案.我不想使用this.Focus(),因为我需要专注于保持不变.

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

创建自己无法选择的按钮类.

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,使用NoSelectButton而不是System的版本更新设计文件.应该在每个实例的两个位置.

Nb:Visual Studio设计器可能会暂时中断其预览,直到您按下"开始".

  • 这具有“PerformClick()”停止触发事件的副作用。但这可以解决:http://stackoverflow.com/questions/16951142/performclick-on-custom-button-will-not-work/31467870#31467870 (2认同)

Ice*_*ind 6

您所要做的就是将此行添加到键Click事件的末尾:

this.Focus();
Run Code Online (Sandbox Code Playgroud)

此行将导致按钮失去焦点,窗体将获得焦点,空格键将无效,从而满足您的2个条件.

现在,如果您不希望再次单击该按钮,则添加以下两行:

this.Focus();
((Button)sender).Enabled = false;
Run Code Online (Sandbox Code Playgroud)

这将执行另一行所做的事情,此外,它将禁用该按钮.

  • 好了它的工作,不得不把焦点按钮点击到另一个可以获得焦点的控件.显然,标签和表单不会像文本框和其他输入元素那样得到关注. (4认同)