C# 拖曳圖片進PictureBox


  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace CSharp_Drag_Picture_To_PictureBox
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18.  
  19. private void Form1_Load(object sender, EventArgs e)
  20. {
  21. foreach (Control items in Controls)
  22. {
  23. if (items.GetType().Name == "PictureBox")
  24. {
  25. items.AllowDrop = true;//允許拖曳
  26. items.DragDrop += Items_DragDrop;
  27. items.DragEnter += Items_DragEnter;
  28. }
  29. }
  30. pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;//PictureBox 顯示模式
  31. }
  32.  
  33. private void Items_DragEnter(object sender, DragEventArgs e)
  34. {
  35. e.Effect = DragDropEffects.All;//拖曳效果
  36. }
  37.  
  38. private void Items_DragDrop(object sender, DragEventArgs e)
  39. {
  40. string filename = (e.Data.GetData((DataFormats.FileDrop)) as string[])[0];//取得檔案位置
  41. if (pictureBox1.Image != null)//判斷PictureBox是否有圖片
  42. {
  43. pictureBox1.Image = null;//清除PictureBox裡的圖片
  44. GC.Collect();//GC收集
  45. }
  46. pictureBox1.Image = Image.FromFile(filename);//顯示
  47. }
  48. }
  49. }


專案下載位置:https://drive.google.com/drive/folders/0B4CEGbmc3kP9eHlrUUxWbGFsNEU?usp=sharing
檔案名稱:CSharp_Drag_Picture_To_PictureBox

留言

這個網誌中的熱門文章

C# 井字遊戲