在一个WINFORM中,我定义了多个按钮,我想实现的逻辑是,点击一个按钮后,如果再点击一个按钮,这两个按钮的名字如果一样的话,两个按钮就消失。
1条回答 默认 最新
- 码老头 2022-02-28 11:06关注
按照惯性,还是先看效果:
步骤和说明都在代码注释里,示例代码如下:
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApp1.Forms.Demo2 { public partial class Form2 : Form { public Form2() { _random = new Random(); InitializeComponent(); } private readonly Random _random; private readonly List<string> _textList = new List<string> { "苹果", "香蕉", "桔子", "草莓" }; // 第一个被点击的按钮 private Button _sourceButton; private void Form2_Load(object sender, EventArgs e) { // 在窗体中初始化20个按钮 for (var i = 0; i < 20; i++) { // 每个按钮的x坐标 var x = (i % 5) * 50 + 5; // 每个按钮的y坐标 var y = (i / 5) * 35; // 按钮实例 var button = new Button { Name = Guid.NewGuid().ToString(), // 按钮的Name属性,这里使用GUID作为惟一标识 Location = new Point(x, y), // 按钮的坐标位置 Size = new Size(50, 30), // 按钮的尺寸 Text = _textList[_random.Next(0, _textList.Count)] // 按钮的显示文本 }; // 注册按钮的点击事件 button.Click += Button_Click; // 将按钮添加到窗体中 Controls.Add(button); } } private void Button_Click(object sender, EventArgs e) { // 当有按钮被点击时,第一个按钮如果为null,则直接把当前按钮赋值给_sourceButton if (_sourceButton == null) { _sourceButton = (Button)sender; label1.Text = $"已选中:{_sourceButton.Text}"; return; } var target = (Button)sender; if (_sourceButton.Name == target.Name) { // 点击的是同一个按钮 return; } // 当被点击的两个按钮的文本相同时,执行消除按钮的操作 if (_sourceButton.Text == target.Text) { // 把第一个按钮从窗体中移除 Controls.Remove(_sourceButton); // 把第二个按钮从窗体中移除 Controls.Remove((Button)sender); // 将第一个按钮变量设置为null _sourceButton = null; label1.Text = "成功消除"; } else { _sourceButton = target; label1.Text = $"已选中:{_sourceButton.Text}"; } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 WPF 大屏看板表格背景图片设置
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示