[英]How could I change the location of a button whenever it is pressed in C#?
我目前正在嘗試在 C# 中制作游戲,其中一個功能是迷你游戲,您必須在其中按下一個按鈕,該按鈕會在點擊后盡可能多地改變位置。
我如何在(12, 105)
和(220, 177)
之間隨機化它的位置? 我正在使用 Visual Studio 2022。
private void button1_Click(object sender, EventArgs e)
{
clicks++;
}
假設你使用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
和Top
屬性。 這適用於 WinForms,但 WPF 具有類似的屬性。下面的代碼演示了兩者:
// 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.