我正在開發一個系統,允許用戶在同一個面板內拖動對象,我經歷了一些研究並發現我應該使用鼠標事件,如mouse_up,mouse_down和mouse_move。C#拖動面板周圍的控件
該程序將生成3個圖片框,並允許用戶拖動面板內的每個圖片框,但程序我的代碼並不完美,因爲當我拖動圖片框時,圖片框會移動,但不會按照到我的鼠標光標位置,這是另一個地方,除了拖動時,面板上有picturebox陰影,我試過update(),refresh()和invalidate(),但它對我來說似乎沒有用。下面是我的代碼,感謝幫助
public partial class Form1 : Form
{
List<PictureBox> pictureBoxList = new List<PictureBox>();
private bool isDragging = false;
public Form1()
{
InitializeComponent();
for (int i = 0; i < 3; i++)
{
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(20, 20),
Location = new Point(i * 40, i * 40),
BorderStyle = BorderStyle.FixedSingle,
SizeMode = PictureBoxSizeMode.Zoom,
ImageLocation = "A.jpg"
};
pictureBoxList.Add(picture);
foreach (PictureBox p in pictureBoxList)
{
p.MouseDown += new MouseEventHandler(c_MouseDown);
p.MouseMove += new MouseEventHandler(c_MouseMove);
p.MouseUp += new MouseEventHandler(c_MouseUp);
pnlDisplayImage.Controls.Add(p);
pnlDisplayImage.Refresh();
}
}
}
void c_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
}
void c_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging == true) {
Control c = sender as Control;
for (int i = 0; i < pictureBoxList.Count(); i++)
{
if (c.Equals(pictureBoxList[i]))
{
pictureBoxList[i].Location = new Point(e.X, e.Y);
}
}
}
}
void c_MouseUp(object sender, MouseEventArgs e)
{
PictureBox c = sender as PictureBox;
isDragging = false;
for (int i = 0; i < pictureBoxList.Count(); i++) {
if (c.Equals(pictureBoxList[i])){
pictureBoxList[i].Location = new Point(e.X, e.Y);
}
}
}
private void pnlDisplayImage_Paint(object sender, PaintEventArgs e)
{
foreach (PictureBox p in pictureBoxList)
{
pnlDisplayImage.Controls.Add(p);
}
}
}
嗨Sinatr,謝謝你的回答,我試着將你的代碼轉換成我的情況,它給了我相同的結果,只是鼠標光標改變了。 我在想是不是我的pnlDisplayImage_Paint事件導致問題 –