Csharp在winform上实现控件拖入的代码
时间: 2024-06-03 21:08:44 浏览: 19
以下是C#在WinForm上实现控件拖入的示例代码:
1. 首先,在窗体上添加一个控件,例如一个PictureBox控件。
2. 在窗体的Load事件中添加以下代码:
private void Form1_Load(object sender, EventArgs e)
{
// 允许拖放操作
this.AllowDrop = true;
// 给PictureBox控件注册拖放事件
this.pictureBox1.DragEnter += new DragEventHandler(pictureBox1_DragEnter);
this.pictureBox1.DragDrop += new DragEventHandler(pictureBox1_DragDrop);
}
3. 实现PictureBox控件的DragEnter事件:
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
// 判断拖入的是不是图片
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
if (file.ToLower().EndsWith(".jpg") || file.ToLower().EndsWith(".jpeg") || file.ToLower().EndsWith(".png"))
{
// 允许拖放操作
e.Effect = DragDropEffects.Copy;
return;
}
}
}
// 不是图片,禁止拖放操作
e.Effect = DragDropEffects.None;
}
4. 实现PictureBox控件的DragDrop事件:
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
// 获取拖入的文件路径
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
// 显示第一张图片
this.pictureBox1.Image = Image.FromFile(files[0]);
}
以上代码实现了在WinForm窗体中拖入图片文件并显示在PictureBox控件中的功能。你可以根据实际需求修改代码。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)