我有一個小問題。我想讓程序可以在多個FlowLayoutPanel之間拖動生成的標籤。但最近幾天我試圖做拖放工作。我嘗試了很多教程,例子等,但它總是有點不同,我不能僅提取基本代碼。C#在FlowLayoutPanels中拖放標籤
它與this program類似,但它在Visual Basic中,我需要它在C#中。我知道這可能很簡單,但我是新手。
謝謝你的幫助。
我有一個小問題。我想讓程序可以在多個FlowLayoutPanel之間拖動生成的標籤。但最近幾天我試圖做拖放工作。我嘗試了很多教程,例子等,但它總是有點不同,我不能僅提取基本代碼。C#在FlowLayoutPanels中拖放標籤
它與this program類似,但它在Visual Basic中,我需要它在C#中。我知道這可能很簡單,但我是新手。
謝謝你的幫助。
實際Drag&Drop
在應用程序之間最有用,也可能在Forms
之間。
假設你想在同一Form
FLPs
之間拖動Labels
,下面的代碼應該讓你去..
它有兩個FlowLayoutPanels
用幾個Labels
初始化它們稱爲FLP1
和FLP2
和開始。
注意三個鼠標事件我添加到每個Label
來模擬Drag&Drop
行動!
private void Form1_Load(object sender, EventArgs e)
{
// create a few Label with varying Colors for testing..
fillFLP(FLP1, 88);
fillFLP(FLP2, 111);
}
void fillFLP(FlowLayoutPanel FLP, int cc)
{
for (int i = 0; i < 24; i++)
{
Label l = new Label();
// the next 3 lines optional and only are there for testing!
l.AutoSize = false;
l.Text = FLP.Name + " " + i.ToString("00");
l.BackColor = Color.FromArgb(255, cc * 2 - i, 255 - 5 * i, cc + 5 * i);
// add controls and set mouse events:
FLP.Controls.Add(l);
l.MouseDown += l_MouseDown;
l.MouseMove += l_MouseMove;
l.MouseUp += l_MouseUp;
}
}
// the currently moved Label:
Label mvLabel = null;
void l_MouseDown(object sender, MouseEventArgs e)
{
// keep reference
mvLabel = (Label)sender;
}
void l_MouseMove(object sender, MouseEventArgs e)
{
// if we are dragging a label:
if (mvLabel != null)
{
// mouse pos in window coords
Point mvPoint = this.PointToClient(Control.MousePosition);
// the label is still in the FLP, so we start the drg action:
if (mvLabel.Parent != this)
{
mvLabel.Parent = this;
mvLabel.Location = mvPoint;
mvLabel.BringToFront();
}
else
{
// we are already in the form, so we just move
mvLabel.Location = mvPoint;
}
}
}
void l_MouseUp(object sender, MouseEventArgs e)
{
// are we over a FLP? and if so which?
Point MP = Control.MousePosition;
FlowLayoutPanel FLP = null;
Point mLoc1 = FLP1.PointToClient(MP);
Point mLoc2 = FLP2.PointToClient(MP);
if (FLP1.ClientRectangle.Contains(mLoc1)) FLP = FLP1;
else if (FLP2.ClientRectangle.Contains(mLoc2)) FLP = FLP2;
else return; // no! nothing we can do..
// yes, now find out if we are over a label..
// ..or over an empty area
mvLabel.SendToBack();
Control cc = FLP.GetChildAtPoint(FLP.PointToClient(MP));
// if we are over the FLP we can insert at the beginning or the end:
// int mvIndex = 0; // to the beginning
int mvIndex = FLP.Controls.Count; // to the end
// we are over a Label, so we insert before it:
if (cc != null) mvIndex = FLP.Controls.IndexOf(cc);
// move the Label into the FLP
FLP.Controls.Add(mvLabel);
// move it to the right position:
FLP.Controls.SetChildIndex(mvLabel, mvIndex);
// let go of the reference
mvLabel = null;
}
這使您可以拖放Lables
並通過降低到Labels
來回兩者之間FLPs
也內FLPs
。
注意,如果你想允許下探Labels
之間,仍然有位置,你將需要一些額外的行..
謝謝,這就是我一直在尋找的東西。 –
這是一個不小的問題。不要拖動控件,使其看起來像[拖動文字](https://social.msdn.microsoft.com/Forums/windows/en-US/36028246-7fc8-4cda-a582-de8a675a0827/drag-text -as形象?論壇=的WinForms)。 –