c# - 如何给每个按钮单独的值
问题描述
我有这个程序可以让按钮在屏幕上移动。我想要实现的是所有按钮都可以朝不同的方向移动。问题是我似乎无法为我的目标找到一个干净的解决方案。到目前为止,这是我的代码。
private void MoveTimer_Tick(object sender, EventArgs e)
{
KeerBewogen++;
foreach (Button button in this.Controls.OfType<Button>())
{
if (KeerBewogen == 150)
{
RichtingX = rnd.Next(-1, 2);
RichtingY = rnd.Next(-1, 2);
KeerBewogen = 0;
}
button.Location = new Point(button.Location.X + RichtingX, button.Location.Y + RichtingY);
if (button.Location.X == 1 || button.Location.Y == 1)
{
RichtingX = rnd.Next(0, 2);
RichtingY = rnd.Next(0, 2);
}
if (button.Location.X == 550 || button.Location.Y == 750)
{
RichtingX = rnd.Next(-1, 0);
RichtingY = rnd.Next(-1, 0);
}
}
if (btnEend1.Location.X == 1 || btnEend1.Location.Y == 1)
{
RichtingX = rnd.Next(0, 2);
RichtingY = rnd.Next(0, 2);
}
if (btnEend1.Location.X == 550 || btnEend1.Location.Y == 750)
{
RichtingX = rnd.Next(-1, 0);
RichtingY = rnd.Next(-1, 0);
}
}
使用此代码,按钮确实以不同的角度在屏幕上移动,但它们都以相同的方式移动。有没有办法为每个按钮单独设置 RichtingY 和 RichtingX?
提前致谢!
解决方案
使用字典来存储按钮和 X、Y 移动值之间的关系 例如:
Dictionary<Button,Tuple<int,int>> angledict = new Dictionary<Button,Tuple<int,int>>();
然后将每个按钮添加到字典中:
foreach (Button button in this.Controls.OfType<Button>()) {
angleDict.Add(button, new Tuple<int,int>(0,0))
}
要更新按钮的位置并更改 X、Y 值:
foreach (Button button in this.Controls.OfType<Button>()) {
**...**
var kvpair = angleDict(button);
button.Location = new Point(button.Location.X + kvpair.Value.Item1, button.Location.Y + kvpair.Value.Item2);
**...**
angleDict(button) = new Tuple<int,int>(rnd.Next(2),rnd.Next(2));
}
推荐阅读
- android - 挣扎着手势拖动
- docker - 无法在无人机 docker build 上标记图像:解析参考时出错:“:最新”不是有效的存储库/标签:参考格式无效
- vb.net - Arint System.Drawing.Graphics 假设写入/修改其附加到的图像?
- java - 多态性:为什么要将接口引用分配给实现该接口的超类的子类
- php - 变量正在执行任务?但显示错误
- java - 在 Spring Boot 2.1.1.RELEASE 中无法访问消息源
- java - 如何创建一个根据时间隐藏其选择项的警报对话框
- javascript - JQuery:添加到 Blogger HTML/Javascript 小工具时代码未运行
- github - 处理大型 MLModel 文件和 Github 存储库
- c - 来自C程序的陷阱命令?