右键单击Windows窗体按钮的操作

时间:2016-05-02 18:34:38

标签: c# winforms

一些快速上下文:在这个项目中,我们使用Visual C#Windows窗体项目来重新创建扫雷。

我正在使用一组Cells(继承自Control.Button)。

作为额外的功劳,我希望用户能够在游戏的课程版本中标记一个单元格。但是,我无法右键单击工作。

在尝试查找解决方案时,我读到您需要将EventArg类型化为MouseEventArg,但这并没有解决我的问题,因为右键单击甚至不会触发我的点击事件。

以下是一些释义代码:

namespace Project_5___Minesweeper_GUI
{
    public partial class Form1 : Form
    {
        public class Cell : Button { /*Custom Cell-Stuff Goes Here*/ }

        Cell[,] board = new Cell[AXIS_LENGTH, AXIS_LENGTH]; //Axis Length is just the dimensions of the board (I use 10x10).

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < AXIS_LENGTH; i++)
            {
                for (int j = 0; j < AXIS_LENGTH; j++)
                {
                    board[i, j] = new Cell();
                    //Set position and size
                    board[i, j].MouseClick += button_arrayClick; //button_arrayClick() is never called by a right-click. Code for it is below. I suspect this line of code has to do with right-clicks not class button_arrayClick().
                    groupBox1.Controls.Add(board[i, j]); //I'm containing the array of Cells inside of a groupbox.
                }
            }
        }

        private void button_arrayClick(object sender, EventArgs e) //Is prepared for handling a right-click, but never receives them.
        {
            Cell temp = (Cell)sender;
            MouseEventArgs me = (MouseEventArgs)e;
            if (me.Button == MouseButtons.Left)
            {
                //Stuff that happens on left-click
            } else {
                //Stuff that happens on right-click
            }
        } 
    }
}

这是我抓住type-casting the event arguments的地方。

3 个答案:

答案 0 :(得分:1)

MouseClick无法处理按钮的右键单击。您可以使用MouseDown

board[i, j].MouseDown += button_arrayClick; 

答案 1 :(得分:1)

改为使用_MouseDown事件。

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        { 
            //stuff that happen on right-click
        }
        else if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            //stuff that happen on left click
        }
    }

auto generate handler in Visual Studio 2013

答案 2 :(得分:0)

收听MouseDown事件

private void button1_MouseDown(object sender, MouseEventArgs e)