实现按键控制窗体移动:
1 打开窗体接收按键事件的属性设置: mform.KeyPreview = true;
2 更改窗体的位置this.Location 的值
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 控制窗体移动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form1 mform = new Form1();//Form1为主窗体名称
mform.KeyPreview = true;//设置窗体接收按键事件
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Point point = this.Location;
switch (e.KeyData)
{
case Keys.Up:
point.Y -= 2;
break;
case Keys.Down:
point.Y += 2;
break;
case Keys.Left:
point.X -= 2;
break;
case Keys.Right:
point.X += 2;
break;
case Keys.Escape:
this.Close();
break;
default:
break;
}
this.Location = point;
}
}
}