我想用c ++格式化一个驱动器,但是当我尝试使用windows.h的Format函数时,我找不到样本或使用它的方法.我也不想让用户进行交互以获得正常或取消所以我不能使用SHFormat
有谁知道我该怎么做?
您可以使用CreateProcess启动cmd.exe格式命令的隐藏副本,并为其提供字符以处理提示.这是在Pascal中,但它是所有API调用,所以它应该很容易翻译.您还需要添加一些错误处理,并确保对其进行广泛测试.
Win32_Volume :: Format仅在Windows 2003中添加,因此如果您需要WinXP或Win2K支持,它将无法运行.
procedure FormatFloppy;
var
sa: TSecurityAttributes;
si: TStartupInfo;
pi: TProcessInformation;
BytesWritten: LongWord;
hInRead, hInWrite: THandle;
begin
// Initialize security information
sa.nLength := SizeOf(sa);
sa.lpSecurityDescriptor := nil;
sa.bInheritHandle := True;
CreatePipe(hInRead, hInWrite, @sa, 0);
// Initialize startup info
ZeroMemory(@si, SizeOf(si));
si.cb := SizeOf(si);
si.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
si.wShowWindow := SW_HIDE;
si.hStdInput := hInRead;
si.hStdOutput := GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError := GetStdHandle(STD_ERROR_HANDLE);
// Start process
ZeroMemory(@pi, SizeOf(pi));
CreateProcess(nil, 'cmd /c format a: /fs:FAT /F:1.44 /V:', nil, nil, True,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, si, pi);
CloseHandle(pi.hThread);
CloseHandle(hInRead);
// Write '<enter>' to start processing, and 'n<enter>' to respond to question at end
WriteFile(hInWrite, #13#10'N'#13#10, 5, BytesWritten, nil);
CloseHandle(hInWrite);
// Wait for process to exit
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
end;
Run Code Online (Sandbox Code Playgroud)