C# Drag and Drop from one Picture box into Another(C# 从一个图片框拖放到另一个图片框)
问题描述
我正在使用 C# 在 Visual Studio 2012 中工作,我需要将一个图片框拖动到另一个图片框,基本上用拖动的图片框图像替换目标图片框图像.
I'm working in visual studio 2012 with C# and I need to Drag a Picture box into another picture box, basically replace the target Picturebox Image with the Dragged Picture box image.
我该怎么做?
请具体说明,并尽量以最简单和最好的方式进行解释.我对编程非常陌生,有点绝望,所以请耐心等待.
Please be specific and try to explain as simplest and as best as possible. I'm extremely new to programming, and a bit desperate so please be patient with me.
推荐答案
在 PictureBox 控件上隐藏了拖放.不知道为什么,它工作得很好.这里可能的指导是,对于用户来说,您可以将图像放在控件上并不明显.您必须对此做一些事情,至少将 BackColor 属性设置为非默认值,以便用户可以看到它.
Drag+drop is hidden on the PictureBox control. Not sure why, it works just fine. The probable guidance here is that it will not be obvious to the user that you could drop an image on the control. You'll have to do something about that, at least set the BackColor property to a non-default value so the user can see it.
无论如何,您需要在第一个图片框上实现 MouseDown 事件,以便您可以单击它并开始拖动:
Anyhoo, you'll need to implement the MouseDown event on the first picturebox so you can click it and start dragging:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
var img = pictureBox1.Image;
if (img == null) return;
if (DoDragDrop(img, DragDropEffects.Move) == DragDropEffects.Move) {
pictureBox1.Image = null;
}
}
我假设您想移动图像,如果需要复制,则在必要时进行调整.然后你必须在第二个图片框上实现 DragEnter 和 DragDrop 事件.由于属性是隐藏的,您应该在表单的构造函数中设置它们.像这样:
I assumed you wanted to move the image, tweak if necessary if copying was intended. Then you'll have to implement the DragEnter and DragDrop events on the second picturebox. Since the properties are hidden, you should set them in the form's constructor. Like this:
public Form1() {
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
pictureBox2.AllowDrop = true;
pictureBox2.DragEnter += pictureBox2_DragEnter;
pictureBox2.DragDrop += pictureBox2_DragDrop;
}
void pictureBox2_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.Bitmap))
e.Effect = DragDropEffects.Move;
}
void pictureBox2_DragDrop(object sender, DragEventArgs e) {
var bmp = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
pictureBox2.Image = bmp;
}
这确实允许您将图像从另一个应用程序拖到框中.让我们称之为功能.如果您想禁止这样做,请使用 bool 标志.
This does allow you to drag an image from another application into the box. Let's call it a feature. Use a bool flag if you want to disallow this.
这篇关于C# 从一个图片框拖放到另一个图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 从一个图片框拖放到另一个图片框
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
