以饼状图来展示当前电脑的磁盘空间
1.获取磁盘信息,想添加 System.Management 的引用.
引用后,读取当前的磁盘
SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
foreach (ManagementObject disk in searcher.Get())
{
zcmb.Items.Add(disk["Name"].ToString());
}
if (zcmb.Items.Count > 0) { zcmb.SelectedIndex = 0; }
2.在当前控件,创建绘画区域进行绘画
获取Graphics区域,创建Pen画笔,然后画数据
private void zcmb_SelectedIndexChanged(object sender, EventArgs e)
{
string name = zcmb.Text;
if (string.IsNullOrEmpty(name)) { return; }
DriveInfo dinfo = new DriveInfo(name);
float tsize = dinfo.TotalSize;
float fsize = dinfo.TotalFreeSpace;
int y = zcmb.Location.Y + 45;
Graphics graphics = this.CreateGraphics();
graphics.Clear(Color.White);
Pen pen1 = new Pen(Color.Red);
Brush brush1 = new SolidBrush(Color.Green);
Brush brush2 = new SolidBrush(Color.Blue);
Font font1 = new Font("Courier New", 16, FontStyle.Bold);
Font font2 = new Font("宋体", 9);
graphics.DrawString("磁盘容量情况", font1, brush1, new Point(60, y));
float angle1 = Convert.ToSingle((360 * (Convert.ToSingle(fsize / 100000000000) / Convert.ToSingle(tsize / 100000000000))));
float angle2 = Convert.ToSingle((360 * (Convert.ToSingle((tsize - fsize) / 100000000000) / Convert.ToSingle(tsize / 100000000000))));
graphics.FillPie(brush1, 60, y + 30, 150, 150, 0, angle1);
graphics.FillPie(brush2, 60, y + 30, 150, 150, angle1, angle2);
graphics.DrawRectangle(pen1, 30, y + 185, 200, 50);
graphics.FillRectangle(brush1, 35, y + 195, 20, 10);
graphics.DrawString("剩余容量:" + FormatFileSize(dinfo.TotalFreeSpace), font2, brush1, 55, y + 195);
graphics.FillRectangle(brush2, 35, y + 215, 20, 10);
graphics.DrawString("已用容量:" + FormatFileSize(dinfo.TotalSize - dinfo.TotalFreeSpace), font2, brush2, 55, y + 215);
}
实现效果如下: