如何使用“空格键或输入”等键盘键停止按下按钮。 C#

我有泡沫应用程序有几个按钮。 当我运行此应用程序时,我可以使用鼠标单击按下这些按钮,也可以使用键盘按下这些按钮。 我不想使用键盘按下这些按钮。

当我点击“Tab”或箭头键“^,v,”时,我也想停止对按钮的关注。

问候

当您需要该行为时,请使用以下代替标准Button

 public class NonSelectableButton : Button { public NonSelectableButton() { SetStyle(ControlStyles.Selectable, false); } } 

编辑:这是一个小测试,certificate它的工作

 using System; using System.Linq; using System.Windows.Forms; namespace Samples { public class NonSelectableButton : Button { public NonSelectableButton() { SetStyle(ControlStyles.Selectable, false); } } static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var form = new Form(); Control[] controls = { new TextBox(), new TextBox(), }; Button[] buttons = { new NonSelectableButton { Text = "Prev" }, new NonSelectableButton { Text = "Next" }, }; foreach (var button in buttons) button.Click += (sender, e) => MessageBox.Show("Button " + ((Button)sender).Text + " clicked!"); int y = 0; foreach (var item in controls.Concat(buttons)) { item.Left = 8; item.Top = y += 8; form.Controls.Add(item); y = item.Bottom; } Application.Run(form); } } } 

EDIT2 ::要应用解决方案,您需要执行以下操作:

(1)将新代码文件添加到项目中,将其命名为NonSelectableButton.cs,其中包含以下内容

 using System; using System.Linq; using System.Windows.Forms; namespace YourNamespace { public class NonSelectableButton : Button { public NonSelectableButton() { SetStyle(ControlStyles.Selectable, false); } } } 

(2)编译项目
(3)现在,新按钮将出现在控件工具箱(顶部)中,您可以将其拖到窗体而不是标准按钮上。

最好的我可以解决停止响应空格键的所有按钮是这样的:

注意:这有点像黑客

将表单的KeyPreview属性设置为true

然后将此代码添加到表单的KeyPress事件中:

 private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (this.ActiveControl is Button && e.KeyChar == (char)Keys.Space) { var button = this.ActiveControl; button.Enabled = false; Application.DoEvents(); button.Enabled = true; button.Focus(); } } 

并且为了阻止控件在标签时获得焦点,只需将按钮的TabStop属性设置为false即可。

看起来你在应用我以前的答案时遇到了麻烦。 这是使用相同想法的另一种方式:

将新代码文件添加到项目中并将以下代码放入其中(确保将YourNamespace替换为您的!)

 using System; using System.Reflection; using System.Windows.Forms; namespace YourNamespace { public static class Utils { private static readonly Action SetStyle = (Action)Delegate.CreateDelegate(typeof(Action), typeof(Control).GetMethod("SetStyle", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(ControlStyles), typeof(bool) }, null)); public static void DisableSelect(this Control target) { SetStyle(target, ControlStyles.Selectable, false); } } } 

然后在Form Load事件中使用它来获取您需要具有该行为的每个按钮。

例如,如果表单包含2个名为btnPrevbtnNext按钮,请在表单加载事件中包含以下行

 btnPrev.DisableSelect(); btnNext.DisableSelect();