如何在代码

时间:2015-09-12 03:23:45

标签: delphi usb

我知道使用此代码格式化哪个驱动器:

function IsRemovableDrive(Drive: Char): Boolean;
begin
Result := (Winapi.Windows.GetDriveType(PChar(Drive + ':\')) = Winapi.Windows.Drive_Removable);
end;

我试过这段代码:

const
SHFMT_DRV_A = 0;
SHFMT_DRV_B = 1;
SHFMT_ID_DEFAULT = $FFFF;
SHFMT_OPT_QUICKFORMAT = 0;
SHFMT_OPT_FULLFORMAT = 1;
SHFMT_OPT_SYSONLY = 2;
SHFMT_ERROR = -1;
SHFMT_CANCEL = -2;
SHFMT_NOFORMAT = -3;

function SHFormatDrive(hWnd: HWND; Drive: Word; fmtID: Word; Options: Word): Longint stdcall; external 'Shell32.dll' Name 'SHFormatDrive';


procedure TForm2.btnFormatClick(Sender: TObject);
var
  FmtRes: Longint;
  cCharTemp : Char;
begin
  try
    cCharTemp := edtDrive.Text[1]; // edtDrive.Tex := 'E';
    FmtRes := ShFormatDrive(Handle, Ord(cCharTemp), SHFMT_ID_DEFAULT, SHFMT_OPT_QUICKFORMAT);
    case FmtRes of
      SHFMT_ERROR: ShowMessage('Error formatting the drive');
      SHFMT_CANCEL: ShowMessage('User canceled formatting the drive');
      SHFMT_NOFORMAT: ShowMessage('No Format')
        else
          ShowMessage('Disk has been formatted!');
    end;
  except
    ShowMessage('Error Occured!');
  end;
end;

当我尝试运行代码时,它总是说“格式化驱动器时出错” 我哪里出错了?

2 个答案:

答案 0 :(得分:3)

最后三个参数是UINT,一个32位类型。声明它们而不是16位Word

驱动器参数记录如下:

  

要格式化的驱动器。此参数的值表示A:驱动器从0开始的字母驱动器。例如,值2代表C:驱动器。

您正在传递该字母的ASCII序号值。您需要将'E'转换为4。也许是这样的:ord(driveChar) - ord('A')

在阅读文档时,请将$0001作为options传递给快速格式。

与使用Windows API一样,请关闭文档:https://msdn.microsoft.com/en-us/library/windows/desktop/bb762169.aspx

你会对那里的评论感兴趣:

  

格式由对话框界面控制。也就是说,用户必须单击“确定”按钮才能实际开始格式化 - 格式无法以编程方式启动。

您的异常处理程序是不必要的,因为try/except块中的任何函数都不会引发异常。

答案 1 :(得分:0)

const
  SHFMT_DRV_A = 0;
  SHFMT_DRV_B = 1;
  SHFMT_ID_DEFAULT = $FFFF;
  SHFMT_OPT_QUICKFORMAT = 0;
  SHFMT_OPT_FULLFORMAT = 1;
  SHFMT_OPT_SYSONLY = 2;
  SHFMT_ERROR = -1;
  SHFMT_CANCEL = -2;
  SHFMT_NOFORMAT = -3;

function SHFormatDrive(
  hWnd: HWND; 
  Drive: UINT; 
  fmtID: UINT; 
  Options: UINT
): DWORD; stdcall; external 'Shell32.dll';

procedure TForm2.btnFormatClick(Sender: TObject);
var
  FmtRes: Longint;
  cCharTemp : Char;
  nDrive : UINT; // this makes all the difference, declare its like this
begin
  try
    cCharTemp := edtDrive.Text[1]; // edtDrive.Text := 'E';
    nDrive := Ord(cCharTEmp) - Ord('A');
    FmtRes := ShFormatDrive(Handle, nDrive, SHFMT_ID_DEFAULT, SHFMT_OPT_QUICKFORMAT);
    case FmtRes of
      SHFMT_ERROR: ShowMessage('Error formatting the drive');
      SHFMT_CANCEL: ShowMessage('User canceled formatting the drive');
      SHFMT_NOFORMAT: ShowMessage('No Format')
        else
          ShowMessage('Disk has been formatted!');
    end;
  except
    ShowMessage('Error Occured!');
  end;
end;

感谢David Heffernan。