winform中窗体重绘、打开目录、查看磁盘剩余空间、注册热键
第一:关于窗体重绘
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; //创建画板,这里的画板是由Form提供的 Rectangle rect = new Rectangle(10, 10, 50, 50);//定义矩形,参数为起点横纵坐标以及其长和宽 //用图片填充 TextureBrush b2 = new TextureBrush(new Bitmap(Properties.Resources.中心图片2)); rect.Location = new Point(0, 0);//更改这个矩形的起点坐标 rect.Width = 700;//更改这个矩形的宽来 rect.Height = 470;//更改这个矩形的高 g.FillRectangle(b2, rect); }
第二:打开目录文件
try { FolderBrowserDialog fbd = new FolderBrowserDialog(); OpenFileDialog ofd = new OpenFileDialog(); // 设置对话框的说明信息 fbd.Description = "请选择下载目录"; if (txtDownFilePath.Text.Trim() != "") { // 获取当前选择的路径并打开 fbd.SelectedPath = txtDownFilePath.Text.Trim(); ofd.InitialDirectory = fbd.SelectedPath; } else { //显示“我的电脑” fbd.RootFolder = Environment.SpecialFolder.MyComputer; } // 允许在对话框中包括一个新建目录的按钮 fbd.ShowNewFolderButton = true; if (fbd.ShowDialog() == DialogResult.OK) { //所选择路径 txtDownFilePath.Text = fbd.SelectedPath; } } catch (Exception ex) { LogHelper.WriteLogError(ex.Message); } }
打开当前目录文件:
//打开当前目录文件 private void lblOpenCurrentPath_Click(object sender, EventArgs e) { string currentpath = txtDownFilePath.Text.Trim(); System.Diagnostics.Process.Start(currentpath); }
第三:获取当前磁盘的剩余空间,发现循环遍历很不错
if (txtDownFilePath.Text.Trim() != "") { string strdisk = txtDownFilePath.Text.Trim(); strdisk = strdisk.Substring(0,3); string freeDisk = string.Empty; double doufreeDisk; int intdisk; DriveInfo[] DviversDisk = DriveInfo.GetDrives(); for (int i = 0;i<DviversDisk.Length;i++) { if (DviversDisk[i].ToString() == strdisk) { freeDisk = DriveInfo.GetDrives()[i].AvailableFreeSpace.ToString(); doufreeDisk = Convert.ToDouble(freeDisk); doufreeDisk = doufreeDisk / 1024 / 1024 / 1024; freeDisk = doufreeDisk.ToString(); freeDisk = freeDisk.Substring(0, 4); lblDiskFreeSpace.Text = freeDisk + "G"; } else { lblDiskFreeSpace.Text = "暂时无法检测到,请联系管理员!"; } } }
第四:主要使用 这两个系统类
[DllImport("user32")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
//注册热键的api
[DllImport("user32")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
需要注意的:
想实现注册类似于ctr+alt+shit+A+Z的方法很简单,将RegisterHotKey的第3个参数设置为KeyModifiers.Alt|KeyModifiers.Control|KeyModifiers.Shift,
第4个参数设置为Keys.B|Keys.Z。
代码:详见sdzn_box