如何创建可点击的标签

Far*_*ABZ 2 c# winforms c#-4.0

我想在表单应用程序中创建一个随机可点击标签.我随机生成了一个标签,但我无法点击它.有谁能够帮我?

Jon*_*eet 31

您可以Click像往常一样挂钩事件:

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 } });
    }
}
Run Code Online (Sandbox Code Playgroud)

这有点奇怪 - 标签显然不是可点击的.

  • 这显然是复活节彩蛋...... (3认同)

Dus*_*gen 7

Jon Skeet为如何动态添加标签提供了一个很好的答案,因此我将添加随机组件.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)