这个例子主要是实现了拖动一个图像到窗体,图像便显示在窗体上你所拖动的位置。
主要是练习了以下的方法。
Control.Invalidate使控件的整个图面无效并导致重绘控件。
如果没有这个方法的话,窗体只是在最大化、最小化或者被覆盖过才进行重画。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Control.Invalidate { /// <summary> /// 这个例子主要是实现了拖动一个图像到窗体,图像便显示在窗体上你所拖动的位置。 /// 主要是练习了以下的方法。 /// Control.Invalidate使控件的整个图面无效并导致重绘控件。 /// </summary> public partial class Form1 : Form { private Image picture; private Point pictureLocation; public Form1() { InitializeComponent(); // Enable drag-and-drop operations and // add handlers for DragEnter and DragDrop. this.AllowDrop = true ; this.DragDrop += new DragEventHandler(Form1_DragDrop); this.DragEnter += new DragEventHandler(Form1_DragEnter); } void Form1_DragEnter(object sender, DragEventArgs e) { //if the data is a file or a bitmap , //display the copy cursor if (e.Data .GetDataPresent (DataFormats .Bitmap )|| e.Data .GetDataPresent (DataFormats .FileDrop )) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } //throw new Exception("The method or operation is not implemented."); } void Form1_DragDrop(object sender, DragEventArgs e) { //handle filedrop data if (e.Data .GetDataPresent (DataFormats .FileDrop) ) { //assign the file names to a string array, //case the user has selected mutiple files string[] files = (string [])e.Data.GetData(DataFormats.FileDrop); try { //assign the first image to the picture variable this.picture = Image.FromFile(files[0]); this.pictureLocation = this.PointToClient(new Point(e.X, e.Y)); } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } //handle bitmap data. if (e.Data.GetDataPresent (DataFormats .Bitmap )) { try { //create an Image and assign it to the picture variable this.picture = (Image )e.Data.GetData(DataFormats.FileDrop); //set the picture location equal to the drop position this.pictureLocation = this.PointToClient(new Point(e.X, e.Y)); } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } //Force the form to be redraw with the image this.Invalidate(); //throw new Exception("The method or operation is not implemented."); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (this.pictureLocation != null && this .picture!= null) { e.Graphics.DrawImage(this.picture, this.pictureLocation); } } } }