C#控件篇 - 鼠标拖动动态添加的控件

项目需要对panel里动态添加的控件可用鼠标移动位置,在csdn上找到一个工程,完全符合要求

记录下来,以备后用

1.核心关键 -- 鼠标事件

为了突出知识产权,以下代码来自:https://download.csdn.net/download/tom_8899/3842222

#region COMMON_MOUSE_EVENT
private Point mouse_offset;
private Point original_pos;
private void Common_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point mousePos = Control.MousePosition;
        mousePos.Offset(mouse_offset.X, mouse_offset.Y);
        //检查是否超出背景图片边界,超出则位置不变;在图片范围内,则控件位置改变。
        if (((Control)sender).Parent.PointToClient(mousePos).X >= 0 && (((Control)sender).Parent.PointToClient(mousePos).X <= ((Control)sender).Parent.BackgroundImage.Size.Width)
            && (((Control)sender).Parent.PointToClient(mousePos).Y >= 0 && ((Control)sender).Parent.PointToClient(mousePos).Y <= ((Control)sender).Parent.BackgroundImage.Size.Height))
        {
            ((Control)sender).Location = ((Control)sender).Parent.PointToClient(mousePos);
            //MessageBox.Show(((Control)sender).Location.ToString());
        }
        else
        {
            ((Control)sender).Location = original_pos;
        }
    }
}
private void Common_MouseDown(object sender, MouseEventArgs e)
{
    mouse_offset = new Point(-e.X, -e.Y);
    original_pos = ((Control)sender).Location;
}

private void Common_MouseMove(object sender, MouseEventArgs e)
{
    ((Control)sender).Cursor = Cursors.Arrow;
    if (e.Button == MouseButtons.Left)
    {
        Point mousePos = Control.MousePosition;
        mousePos.Offset(mouse_offset.X, mouse_offset.Y);
        ((Control)sender).Location = ((Control)sender).Parent.PointToClient(mousePos);
    }
}
#endregion

上面代码的优点在于:Common_MouseUp中对当前位置进行判断,是否超出控件的父控件范围。

这一点给相关类似操作提供实现思路!!

2.动态生成控件

下面的代码是我自己滴

PictureBox m_pBeamPicBox = new PictureBox[nums];
for (int i = 0; i < nums; i++)
{
    m_pBeamPicBox[i] = new System.Windows.Forms.PictureBox();
    m_pBeamPicBox[i].SizeMode = PictureBoxSizeMode.AutoSize;    // 控件大小与图片一致
    m_pBeamPicBox[i].BackColor = Color.Transparent;             // 背景透明
    m_pBeamPicBox[i].Image = (Bitmap)(m_rm.GetObject("N" + (i + 1).ToString()));
    m_pBeamPicBox[i].MouseMove += new System.Windows.Forms.MouseEventHandler(Common_MouseMove);
    m_pBeamPicBox[i].MouseDown += new System.Windows.Forms.MouseEventHandler(Common_MouseDown);
    m_pBeamPicBox[i].MouseUp += new System.Windows.Forms.MouseEventHandler(Common_MouseUp);
    panelSteelBeam.Controls.Add(m_pBeamPicBox[i]);
}

这里的关键是给控件添加鼠标事件。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值