在 DragDrop 生成的方法中添加代碼以下:windows
private void Form1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Move; } else { e.Effect = DragDropEffects.None; } }
在 DragEnter 方法中添加代碼以下: spa
private void Form1_DragEnter(object sender, DragEventArgs e) { //判斷 string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; string file = files[0]; if (!file.ToLower().EndsWith(".png") && !file.ToLower().EndsWith(".jpg")) { MessageBox.Show("須要圖片文件!"); return; } //PictureBox控件顯示圖片 Image.Load(file); }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { //PictureBox控件顯示圖片 Image.Load(openFileDialog.FileName); } }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { //PictureBox控件顯示圖片 Image.Load(openFileDialog.FileName); //獲取用戶選擇文件的後綴名 string extension = Path.GetExtension(openFileDialog.FileName); //聲明容許的後綴名 string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" }; if (!str.Contains(extension)) { MessageBox.Show("僅能上傳gif,jpge,jpg格式的圖片!"); } else { //獲取用戶選擇的文件,並判斷文件大小不能超過20K,fileInfo.Length是以字節爲單位的 FileInfo fileInfo = new FileInfo(openFileDialog.FileName); if (fileInfo.Length > 20480) { MessageBox.Show("上傳的圖片不能大於20K"); } else { //絕對路徑 string image = openFileDialog.FileName; // 是指XXX.jpg string picpath = openFileDialog.SafeFileName; File.Copy(openFileDialog.FileName, Application.StartupPath + "\\Image\\" + picpath); } } } }