首页 > 解决方案 > Lambda 表达式无法识别鼠标右键

问题描述

下面的代码从一个数组创建一个 5 x 5 的按钮网格。我正在使用 lambda 表达式在鼠标单击时获取按钮在数组中的位置。问题是,我需要知道是否按下了鼠标左键或右键。到目前为止,我已经从左侧按钮输出,但右侧没有响应。

    Button[] grid5x5 = new Button[25];
    void Spawn5x5Grid()
    {
        lblSize.Text = "5x5";
        currentGridSize = GridSize.grid5x5;
        currentGameState = GameState.GameOn;

        // Position of the first button
        int x = 50, y = 150;
        // Index of the button for the loop
        int count = 0;
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                grid5x5[count] = new Button
                {
                    Size = new Size(31,31),
                    Location = new Point(x, y)
                };
                this.Controls.Add(grid5x5[count]);

                grid5x5[count].MouseClick += (o, ee) =>
                {
                    Button button = o as Button;

                    int index = Array.IndexOf(grid5x5, button);

                    if (ee.Button == MouseButtons.Left)
                    {
                        Console.WriteLine("Left button");   
                    }
                    else if (ee.Button == MouseButtons.Right)
                    {
                        Console.WriteLine("Right button");
                    }

                };

                count++;
                x = x + 31;
            }
            x = 50;
            y = y + 31;
        }
    }

标签: c#.netwinformslambdamouse

解决方案


推荐阅读