网站首页 > 基础教程 正文
一、演示
二、功能
1、PictureBox控件显示拖拽到其中的图片;
2、显示图片的路径、大小等相关信息;
三、代码及说明
为实现拖拽,需将pictureBox1控件的AllowDrop属性设置为True,即:
this.pictureBox1.AllowDrop = true;
将该控件的图片布局属性设置为Zoom(按比例缩放):
为该控件添加DragEnter方法:
完整程序如下:
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace FileDragDrop
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.pictureBox1.AllowDrop = true;//允许拖拽
}
//调用API中获取文件大小的方法
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint GetCompressedFileSize(string fileName, ref uint fileSizeHigh);
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);//检查拖动目标类型,是文件时执行
Bitmap bgImage = new Bitmap(str_Drop[0]);//初始化该文件路径的图片
pictureBox1.BackgroundImage = bgImage;//显示图片
label1.Text = str_Drop[0].ToString();//路径
label2.Text = bgImage.Width.ToString() + " × " + bgImage.Height.ToString();//像素
var ext = Path.GetExtension(str_Drop[0]);
label4.Text = ext.ToString(); //格式
uint size = 0; //大小
uint lsize = GetCompressedFileSize(str_Drop[0], ref size);
ulong rsize = ((ulong)size << 32) + lsize;
switch (rsize)//判断图片大小范围
{
case ulong n when n < 1024:
label3.Text = n.ToString() + "字节";
break;
case ulong n when n >= 1024 && n < 1024 * 1024:
label3.Text = ((float)n / 1024).ToString("F1") + "KB";//保留1位小数
break;
case ulong n when n >= 1024 * 1024:
label3.Text = ((float)n / 1024 / 1024).ToString("F2") + "MB";//保留2位小数
break;
}
}
}
}
四、参考及延伸
猜你喜欢
- 2024-10-12 340.C# 中最有价值的语法糖及其应用场景
- 2024-10-12 Dev——手把手教你学会CheckedListBox(C#)
- 2024-10-12 流程控制-循环语句(5-5)-C#编程零基础到入门学习
- 2024-10-12 C#12那些有意思的特性 c# 特性的实现原理
- 2024-10-12 C#得到网关和DNS地址 .netcore 网关
- 2024-10-12 C#设计模式之4-原型模式 c++原型模式
- 2024-10-12 C#05(判断、循环语句) c#循环次数由什么决定
- 2024-10-12 C#:编程界的全能王,其他语言只能望尘莫及?
- 2024-10-12 C# 中的模式匹配与安全的类型转换:is 和 as 运算符的深入解析
- 2024-10-12 C# 循环语句介绍 c#循环输出
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)