How to stop pressing button using keyboard keys like “Spacebar or Enter”. C#

前端 未结 3 1905
长发绾君心
长发绾君心 2020-12-22 01:09

I have win-foam application having several buttons. When i run this application, i am able to press these buttons using mouse click also able to press these buttons using ke

3条回答
  •  梦毁少年i
    2020-12-22 01:16

    Looks like you have troubles applying my previous answer. Here is another way using the same idea:

    Add a new code file to your project and put the following code inside (make sure to replace YourNamespace with yours!)

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

    Then use it inside your Form Load event for each button you need to have that behavior.

    For instance, if your form contains 2 buttons called btnPrev and btnNext, include the following lines in your form load event

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

提交回复
热议问题