[英]How could I change the location of a button whenever it is pressed in C#?
I am currently trying to make a game in C#, and one of the features is a minigame in which you have to press a button which changes location upon click as many times as you can.我目前正在尝试在 C# 中制作游戏,其中一个功能是迷你游戏,您必须在其中按下一个按钮,该按钮会在点击后尽可能多地改变位置。
How could I randomise the location of it between (12, 105)
and (220, 177)
?我如何在
(12, 105)
和(220, 177)
之间随机化它的位置? I'm using Visual Studio 2022.我正在使用 Visual Studio 2022。
private void button1_Click(object sender, EventArgs e)
{
clicks++;
}
Assuming that you use WinForms , you can put it as follow:假设你使用WinForms ,你可以这样说:
static readonly Random s_Random = new Random();
private void button1_Click(object sender, EventArgs e) {
clicks++;
button1.Location = new Point(
s_Random.Next(12, 220 + 1), // x (left) in [12..220] range
s_Random.Next(105, 177 + 1) // y (top) in [105..177] range
);
}
Random rand = new Random();
int val = rand.Next(a, b+1);
Left
, and Top
properies.Left
和Top
属性。 This applies to WinForms, but WPF has similar properties. The code below demonstrates both:下面的代码演示了两者:
// Can be kept as a class member:
Random rand = new Random();
// Note: change x1,x2,y1,y2 below to control the range for locations.
int x1 = 12;
int x2 = 220;
int y1 = 105;
int y2 = 177;
// Randomize location in the defined range:
int x = rand.Next(x1, x2 + 1);
int y = rand.Next(y1, y2 + 1);
// Move the button:
button1.Left = x;
button1.Top = y;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.