如何使用UP和DOWN键进行编码 [英] How to code at the UP and DOWN key

查看:115
本文介绍了如何使用UP和DOWN键进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下"UP"和"DOWN"键时,我想上下移动图片框.

I want to move picture box up and down when a user press ''UP'' and ''DOWN'' Key

推荐答案

您的问题是当您如果可以从表单中获取焦点,则可以控制表单.
另外,在其他解决方案中,我看不到将事件处理程序添加到事件实例的位置.

因此,这是 real 解决方案:
Your problem is when you have a control on the form, if can grab the focus out of the form.
Also, in other solutions I don''t see where the event handler is added to an event instance.

So, here is the real solution:
int Increment = //...
PictureBox myPictireBox = //...

myForm.KeyPreview = true; //this is important!
myForm.KeyDown += (sender, eventArgs) => {
    clientHeight = myForm.ClientSize.Height;
    if (eventArgs.KeyCode = Keys.Up && myPictireBox.Top > 0) //NOT KeyData!
       myPictireBox.Top -= Increment;
    else if (eventArgs.KeyCode = Keys.Down && myPictireBox.Top < height - myPictireBox.Height) //NOT form's height
       myPictireBox.Top += Increment;
} //myForm.KeyDown



修复此问题的方法:1)在预览中引发事件,因此具有焦点的孩子不会抓住它; 2)更正了键码的使用; 3)更正了客户的身高.

对于C#v.2的用户,添加带有"+ ="的处理程序应该有点不同.代替



The fixes here: 1) event is raised in preview, so children having focus won''t grab it, 2) corrected use of key code, 3) corrected client height.

For users of C# v.2, adding the handler with "+=" should be a bit different. Instead of

myForm.KeyDown += (sender, eventArgs) => { /* ... */ }







write

myForm.KeyDown += delegate(object sender, System.KeyEventArgs eventArgs) { /* ... */ }



祝你好运,

—SA



Good luck,

—SA


您没有提到任何按钮,所以我以form1_keydownevent
的形式编写了它
抱歉,如果您误解了您的问题

you are not mentioning any buttons or else so i wrote it in form1_keydownevent

sorry if misunderstand your question

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Up)
            {
                if (picbox1.Top > 0)
                    picbox1.Top = picbox1.Top - 10;
            }
            if (e.KeyData == Keys.Down)
            {
                if (picbox1.Top <= (this.Height-picbox1.Height))
                    picbox1.Top = picbox1.Top + 10;
            }
        }


Point p = MyPictureBox.Location;
p.Y = p.Y++; //p.Y--; to move DOWN
Location = p.X;
MyPictureBox.Location = p;


这篇关于如何使用UP和DOWN键进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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