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

问题描述

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

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

推荐答案

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


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键进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:04