按键时动态移动窗体c#
本文关键字:窗体 移动 动态 | 更新日期: 2023-09-27 18:22:48
当我按下A
按钮时,我需要移动表单位置,但不是只有一次,每次按下A
按钮,表单都应该出现在不同的位置
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A) // First time I press A
form.Location = location1;
if (e.KeyCode == Keys.A)
form.Location = location2; // second time I press A
if (e.KeyCode == Keys.A)
form.Location = location3; // 3rd time I press A
}
所以当我第一次按"A"时,表格将在位置1,如果第二次它将在位置2,如果第三次它将位于位置3,如果第四次它应该返回位置1…
有什么想法吗?
我试着用int变量来检查它是第一次还是第二次或第三次,但不起作用。。。
只需放置一个基本计数器并使用模运算符。
private int timeKeyPress = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Point locations = new Point[] {location1, location2, location3 };
if (e.KeyCode == Keys.A)
{
form.Location = locations[timeKeyPress++ % locations.Length];
}
}
这假设如果按A超过2147483647次,则应用程序将无法连接到IndexOutOfRangeException
。
我认为您需要将location1、location2、location3存储在数组或列表中
List<Point> arr_points = new List<Point>();
然后你需要在表单加载中填写这些位置,例如
private void Form1_Load(object sender, EventArgs e)
{
arr_points.Add(new Point(166, 516));
arr_points.Add(new Point(36, 516));
arr_points.Add(new Point(0, 0));
}
将int
变量作为计数器
int i = 0;
然后你需要在key_down
检查,如果这个i
大于arr_points
,那么它应该再次为0,否则你需要增加它i++
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (i == arr_points.Count)
{
i = 0;
}
if (e.KeyCode == Keys.A)
this.Location = arr_points[i];
i++;
}
因此,整个代码将类似于以下代码:
List<Point> arr_points = new List<Point>();
int i = 0;
private void Form1_Load(object sender, EventArgs e)
{
arr_points.Add(new Point(500, 400));
arr_points.Add(new Point(25, 516));
arr_points.Add(new Point(0, 0));
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (i == arr_points.Count)
{
i = 0;
}
if (e.KeyCode == Keys.A)
this.Location = arr_points[i];
i++;
}