项目需要对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]);
}
这里的关键是给控件添加鼠标事件。