[英]How to drag and drop one image in a picture box on top of another in another picturebox in C#?
我的Windows窗體應用程序中有兩個圖片框。 這些圖片框均保存一個圖像。 pictureBox1小,只有122 x 52,pictureBox2大得多(459 x 566)。 我想要做的是能夠將picturebox1的圖像拖放到picturebox2上,然后將創建並保存一個新圖像。 無論我將x&y坐標放置在pictureBox1的圖像中,它將在“圖片框2”中的該位置“蓋章”。 然后pictureBox2的圖像將被修改並保存。 因此,只需通過拖放操作,用戶就可以輕松地將圖像“蓋章”到pictureBox2上。 這可能嗎?
斯努布先生
如果使用拖放,則可以控制您要執行的操作。 通常,在控件的MouseDown事件中,您確定DragEvent是否正在啟動。 我保留一個表單屬性。
private Point _mouseDownPoint;
我在MouseDown期間將其設置為拖動控件
protected override void OnMouseDown(MouseEventArgs e)
{
_mouseDownPoint = e.Location;
}
在同一控件的OnMouseMove事件中。 此代碼可確保用戶最有可能嘗試拖動並開始拖放操作。 該代碼來自用戶控件,因此在您的情況下,可能必須更改DoDragDrop中的this。
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button != MouseButtons.Left) return;
var dx = e.X - _mouseDownPoint.X;
var dy = e.Y - _mouseDownPoint.Y;
if (Math.Abs(dx) > SystemInformation.DoubleClickSize.Width || Math.Abs(dy) > SystemInformation.DoubleClickSize.Height)
{
DoDragDrop(this, DragDropEffects.Move);
}
}
可能收到該放置的控件應將其DragEnter事件編碼。 在這里,我們有一個DragEnter事件,用於區分ToolStripButton和自定義UserControl DSDPicBox。 沒有代碼的DragEnter事件的控件將在拖動時顯示noDrop圖標。
private void Control_DragEnter(object sender, DragEventArgs e)
{
var button = e.Data.GetData(typeof(ToolStripButton)) as ToolStripButton;
if (button != null)
{
e.Effect = DragDropEffects.Copy;
return;
}
var element = e.Data.GetData(typeof(DSDPicBox)) as DSDPicBox;
if (element == null) return;
e.Effect = DragDropEffects.Move;
}
最后,您必須處理下降。 panelDropPoint是放置項目的位置的坐標。 您可以使用它來將新圖形放置在舊圖形中。 如果要更改圖片的大小,則必須以新的分辨率渲染圖片。
private void panel_DragDrop(object sender, DragEventArgs e)
{
// Test to see where we are dropping. Sender will be control on which you dropped
var panelDropPoint = sender.PointToClient(new Point(e.X, e.Y));
var panelItem = sender.GetChildAtPoint(panelDropPoint);
_insertionPoint = panelItem == null ? destination.Controls.Count : destination.Controls.GetChildIndex(panelItem, false);
var whodat = e.Data.GetData(typeof(ToolStripButton)) as ToolStripButton;
if (whodat != null)
{
//Dropping from a primitive button
_dropped = true;
whodat.PerformClick();
return;
}
}
我已經從代碼中刪除了一些會使您感到困惑的項目。 此代碼可能開箱即用,但可以使您更加接近。
問候,馬克
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.