【问题标题】:How to get Windows for to raise mouseclick event for programatically created PictureBox?如何让 Windows 为以编程方式创建的 PictureBox 引发鼠标单击事件?
【发布时间】:2012-10-12 23:10:57
【问题描述】:

我正在构建一个虚拟棋盘游戏,我需要能够点击棋子来移动它们。该板在背景中创建为图片,并且这些部分是顶部的图片框。更具体地说,它们是继承自 PictureBox 的自定义类 GamePiece。我知道 PictureBox 有一个 Name_Click 方法,在单击它时会调用它,但我正在以编程方式创建我的作品,如下所示:

    public Player(int identity, GameBoard Board)
    {
        ID = identity;
        for (int i = 0; i < 4; i++)
        {
            Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
        }
    }

因此,我不想在为每个 Gamepiece 调用的方法中硬编码,因为这会破坏我的目的。

有什么建议吗?我可以包含任何其他有用的代码,而且我在重新设计代码方面非常灵活,如果这会让我以后的生活更轻松的话。提前致谢。

【问题讨论】:

    标签: c# winforms events


    【解决方案1】:

    (连接到事件处理程序)

    Pieces[i].Click += new EventHandler(theOnClickEvent);
    

    (事件处理程序)

    void theOnClickEvent(object sender, EventArgs e)
        {
            //clicked.
        }
    

    【讨论】:

      【解决方案2】:

      可能是:

      gamePiece.Click += myEventHandler;
      

      其中gamePieceGamePiece 对象,myEventHandler 是任何形式的事件处理程序...委托、lambda 等等。

      【讨论】:

        【解决方案3】:

        只需为您的控件添加Control.Click 事件处理程序:

        public Player(int identity, GameBoard Board)
        {
            ID = identity;
            for (int i = 0; i < 4; i++)
            {
                Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
                Pieces[i].Tag = ID;
                Pieces[i].Click += pieces_Click;
            }
        

        关于Click 事件:

        private void pieces_Click(object sender, EventArgs e)
        {
            int id = (int) ((Pieces))sender.Tag;
            DoSomethingForId(id);
        }
        

        或使用Anonymous Methods:

        public Player(int identity, GameBoard Board)
        {
            ID = identity;
            for (int i = 0; i < 4; i++)
            {
                Pieces[i] = new ....
                Pieces[i].Click += (sender, e) =>
                                {
                                    // Do some thing
                                };
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多