简体   繁体   English

如何使KeyPress事件处理程序可用于所有表单?

[英]How do I make KeyPress event handler available to all forms?

I've created a KeyPress event handler that prevents the entry of anything but digits, decimals, and backspace in any subscibing input control. 我已经创建了一个KeyPress事件处理程序,可以防止在任何子文档输入控件中输入除数字,小数和退格之外的任何内容。 The problem is that the handler is only available to the form within which it was created. 问题是处理程序仅可用于创建它的表单。 Rather than copying the event handler to every form, is there a way to make it global - so that the keypress event of any input control on any form can subscribe to it. 不是将事件处理程序复制到每个表单,有没有办法使其成为全局 - 以便任何表单上的任何输入控件的按键事件都可以订阅它。

Thank you. 谢谢。

Another more object oriented solution would be to inherit from the TextBox control and override the KeyPress event, creating your own custom type of TextBox. 另一个面向对象的解决方案是继承TextBox控件并覆盖KeyPress事件,创建自己的自定义TextBox类型。

class NumericTextBox : System.Windows.Forms.TextBox
{
    protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        if (true /* insert your conditions */)
            e.Handled = true;
    }
}

Then use this control where needed in place of the regular TextBox control. 然后在需要的地方使用此控件代替常规TextBox控件。

Make it public and static, and you should probably move it to a "Utilities" type class. 将其设置为公共和静态,您应该将其移动到“Utilities”类型类。 (Or its own class) (或者它自己的班级)

namespace GlobalKeyPress
{
    public class GlobalKeyPress
    {
        public static void KeyPressFilter(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '.')
                e.Handled = true;
        }
    }
}

Delegates are normal objects, and as such, you can return them from methods. 委托是普通对象,因此,您可以从方法返回它们。

Specifically, you'd want to create a KeyPressEventHandler delegate 具体来说,您需要创建一个KeyPressEventHandler委托

public static class Utilities
{
    private static KeyPressEventHandler handler = KeyPressed;

    public static void KeyPressed(Object sender, KeyPressEventArgs e)
    {
        // Your logic here
    }

    public static KeyPressEventHandler getKeyPressHandler() {
        return handler;
    }
}

Note: I haven't tested this, though. 注意:我没有测试过这个。 It looks correct as per the pages on Using Delegates and KeyPressEventHandler 根据Using DelegatesKeyPressEventHandler上的页面,它看起来是正确的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM