在一些特殊项目中,需要对系统硬盘进行格式化,该操作是非常危险的,所以程序要控制好.
1.[DllImport("shell32.dll")] 操作
[DllImport("shell32.dll")]
private static extern int SHFormatDrive(IntPtr hWnd, int drive, long fmtID, int Options);
public const long SHFMT_ID_DEFAULT = 0xFFFF;
2.执行格式化操作
private void fMain_Load(object sender, EventArgs e)
{
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; }
}
private void zbtnsubmit_Click(object sender, EventArgs e)
{
string name = zcmb.Text;
if (string.IsNullOrEmpty(name)) { return; }
if (MessageBox.Show("是否确认格式化磁盘") == DialogResult.Yes)
{
try
{
SHFormatDrive(this.Handle, zcmb.SelectedIndex, SHFMT_ID_DEFAULT, 0);
MessageBox.Show("格式化完成", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("格式化失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}