C#keypress事件多次触发 [英] C# keypress event fires to many times

查看:784
本文介绍了C#keypress事件多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定。我的问题是,当我在表单中并按F5时,它就像一个魅力,我的所有数据和控件都会更新。第二次按F5,它会两次触发frmarbeidsplan_keydown(?),第三次触发事件4次,然后8次16次。



每次我按F5的时间是我按下它的次数加倍并循环代码。我不明白为什么?







Ok. My problem is that when i am in the form and press F5 it works like a charm and all my data and controls are updated. Second time i press F5 it fires the frmarbeidsplan_keydown twice (?), and the third time it fires the event 4 times, and then 8 times and 16 times.

Every time i press F5 it doubles the amount of times i have pressed it and loops the code. I cannot understand why?



private void frmArbeidsplan_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.F5)
     {
         MessageBox.Show("F5");
         e.SuppressKeyPress = true;
         e.Handled = true;
         OppdaterSkjema();
     }

 }













//Refresh skjema med data
        private void OppdaterSkjema()
        {
            if (this.lOG_ArbeidsplanDataGridView.IsCurrentCellInEditMode)
            {
                this.Validate();
                this.lOG_ArbeidsplanDataGridView.EndEdit();
                this.lOG_ArbeidsplanBindingSource.EndEdit();
                this.lOG_ArbeidsplanTableAdapter.Update(this.dataSetApoLogiDose);
            }
            OppdaterStatus(0, 1, 5, "Fjerner objekter fra skjema");

            Form.ControlCollection fObjs = (ControlCollection)this.Controls;
            int i = fObjs.Count;

            while (i != 0)
            {
                fObjs[0].Dispose();
                i = i - 1;
            }


            this.InitializeComponent();
            this.frmArbeidsplan_Load(sndr, es);
            OppdaterStatus(-1, 4, 5, "Siste lasting:" + DateTime.Now.ToLongTimeString());


        }

推荐答案

在按键事件中,您正在调用OppdaterSkjema()然后这个叫:this.frmArbeidsplan_Load(sndr,es);



在表单加载方法中,它再次挂起了按键事件。因此当你按一个键时,它会比上一次更多地调用该事件。



去除对Load的调用,或者移除除Initialize()之外的所有内容加载方法和可以被多次调用的另一个方法。
On the keypress event, you are calling OppdaterSkjema() which then calls this: this.frmArbeidsplan_Load(sndr, es);.

In the form load method, it is hooking up the keypress event again. So when you press a key, it calls the event one more time than last time.

Get rid of the call to Load, or move everything but Initialize() out of the load method and into a different one that can be called more than once.


如果你通过重新安排InitializeComponentor构造函数感到困难,只需按照方法。



简单来说,只需添加

If you felt difficulties by re arranging the InitializeComponentor construcors, just follow the method.

In simple, Just add
void onKeyPressEvent(object sender, KeyEventArgs e)
{
if(e.Handled)
return;

{
//
// the block of codes to be executed on the key press
// should added here.
//
}
e.Handled = true;
}


这篇关于C#keypress事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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