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(),因为我需要专注于保持不变.
创建自己无法选择的按钮类.
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设计器可能会暂时中断其预览,直到您按下"开始".
您所要做的就是将此行添加到键Click事件的末尾:
this.Focus();
Run Code Online (Sandbox Code Playgroud)
此行将导致按钮失去焦点,窗体将获得焦点,空格键将无效,从而满足您的2个条件.
现在,如果您不希望再次单击该按钮,则添加以下两行:
this.Focus();
((Button)sender).Enabled = false;
Run Code Online (Sandbox Code Playgroud)
这将执行另一行所做的事情,此外,它将禁用该按钮.
| 归档时间: |
|
| 查看次数: |
27205 次 |
| 最近记录: |