简体   繁体   English

C#中的应用程序级键过滤器

[英]Application-wide key-filter in C#

I want my Win-Forms application (which has many different forms) to accept only certain characters of user input. 我希望Win-Forms应用程序(具有许多不同的表单)仅接受用户输入的某些字符。 This restriction should apply to all forms, all input fields, etc. Is there any simple solution to implement this without adding keyboard-events to every single form and even better, without changing any existing form? 此限制应适用于所有表单,所有输入字段等。是否有任何简单的解决方案可以实现而无需在每个表单中添加键盘事件,甚至更好,而无需更改任何现有表单?

First I have thought of a low-level keyboard hook but this would be applied globally to every user input in every application running on the system which isn't the ideal solution, I guess. 首先,我想到了一个低级的键盘挂钩,但是我想这将被全局地应用于系统上运行的每个应用程序中的每个用户输入,这不是理想的解决方案。 Any other possibilities or suggestions? 还有其他可能性或建议吗?

You can do that if you create a custom control for each control you need and set your control to inherit the core controls. 如果您为所需的每个控件创建一个自定义控件,并将控件设置为继承核心控件,则可以执行此操作。 For example, this code will prevent clicking on zero: 例如,此代码将防止单击零:

public class MyTextBox : TextBox
{
    protected override void OnKeyUp(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.D0)
            e.SuppressKeyPress = true;
    }
}

You can even drag this control from the toolbox (after you build). 您甚至可以从构建工具箱中拖动此控件。

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

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