I want to create a random clickable label in my form application. I randomly generated a label but I can not click on it. Can any body help me?
Asked
Active
Viewed 1.4k times
2
-
1What problem faced when use button..? – bgs Jul 08 '13 at 11:00
-
1http://stackoverflow.com/questions/6293588/how-to-create-an-html-checkbox-with-a-clickable-label This is can help you – Alex Jul 08 '13 at 11:02
-
Are you aware of the flat button style? (If this is for flat looking buttons) – Sayse Jul 08 '13 at 11:14
2 Answers
32
You can just hook into the Click
event as normal:
using System.Windows.Forms;
class Test
{
static void Main()
{
Label label = new Label { Text = "Click me" };
label.Click += delegate { label.Text = "Clicked"; };
Application.Run(new Form { Controls = { label } });
}
}
It's a little odd though - labels aren't obviously clickable.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
3
-
It's surprising that labels are not obviously clickable since they aid with accessibility issues. They are used extensively as clickable objects in web development. We tend to style them so that the cursor is a pointer to make it more obvious. – James South Jul 08 '13 at 13:38
7
Jon Skeet provided an excellent answer on how to add a label dynamically, so I will add the random component.
using System.Windows.Forms;
class Program
{
private static Random Random = new Random();
static void Main()
{
var label = new Label { Text = "Click me!" };
label.Click += delegate { RandomizeLocation(label); };
EventHandler Load = delegate {
RandomizeLocation(label);
};
var form = new Form { Controls = { label } };
form.Load += Load;
Application.Run(form);
}
private static void RandomizeLocation(Control control)
{
var maxWidth = control.Parent.Width - control.Width;
var maxHeight = control.Parent.Height - control.Height;
var x = Random.Next(maxWidth);
var y = Random.Next(maxHeight);
control.Location = new Point(x, y);
}
}

Dustin Kingen
- 20,677
- 7
- 52
- 92