gpt4 book ai didi

c# - c# 按下按键动态移动表单

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:52 25 4
gpt4 key购买 nike

我需要在按下 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 变量来检查它是第一次还是第二次或第三次,但不起作用...

最佳答案

只需放置一个基本计数器并使用 modulo operator .

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 超过 2,147,483,647 次,应用程序将无法IndexOutOfRangeException

关于c# - c# 按下按键动态移动表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com