按键事件超载我 [英] key press event overloading i

查看:62
本文介绍了按键事件超载我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace HUMAN_RESOURCES.MANAGEMENT
{
    class function
    {
        public void keypress(object Sender, KeyPressEventArgs e)
        {
            int x = e.KeyChar;
            if (x != 8)
            {
                if (!(x >= 48 && x <= 57))
                    e.Handled = true;
            }
        }
    }
}


这是我的课,如果我写了数字的按键事件代码,
我想以其他形式调用此代码

我可以通过重载使用此代码的地方,请帮助我,,


this is my class were i have written a key press event code for numbers,
i want to call this code in my different form

where i can use this code by overloading please help me i am in trouble ,,,

推荐答案

您不能.
这与重载无关.

重载:具有相同方法的不同版本,但参数不同.例如:
You can''t.
That has nothing to do with overloading.

Overloading: Haveing different versions of the same method, distinguished by having differing parameters. For example:
public void Print(int i) { Console.WriteLine("Integer: {0}", i);}
public void Print(float f) { Console.WriteLine("Float: {0}", f);}



您要做的是从许多不同的文件中调用与事件处理程序相同的方法.
您要尝试做的是使其成为static-这意味着它是共享的,并且没有引用它所属的类的任何特定实例.但这也不起作用,因为设计人员在添加eveny处理程序时总是引用类实例:



What you want to do is call the same method as an event handler from many different files.
What you are trying to do is to make it static - which means it is shared and does not refer to any specific instance of the class it is a part of. But that won''t work either, because the designer always refers to the class instance when adding eveny handlers:

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MyForm_KeyDown);


因此,最好的办法是声明一个static方法,该方法接受KeyPressEventArgs并从每个单独的处理程序中调用它:


So, the best you can do is declare a static method, which accepts the KeyPressEventArgs and call it from each of your individual handlers:

public static void IgnoreUnwantedKeys(KeyPressEventArgs e)
{
    int x = e.KeyChar;
    if (x != 8)
    {
        if (!(x >= 48 && x <= 57))
            e.Handled = true;
    }
}


public void keypress(object Sender, KeyPressEventArgs e)
{
    function.IgnoreUnwantedKeys(e);
}


这篇关于按键事件超载我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆