问题
I asked on the Lazarus programming forum how to open a physical disk. I want to allow the user to select physical disks from their system when they click a "Select Disk" button. There are some examples here at Stack Overflow that are similar but not quite the same (such as Delphi - Using DeviceIoControl passing IOCTL_DISK_GET_LENGTH_INFO to get flash media physical size (Not Partition)).
There are lots of C and C++ examples of using CreateFile
(in the documentation and especially an example of calling DeviceIoControl) but I can't find any for Free Pascal or Delphi and I am not good enough yet to work out how to do it.
Can anyone point me in the direction of a link that explains it or better still an actual example written in Delphi or Free Pascal? Can anyone help me understand how to use it?
回答1:
Your C example has this code:
/* LPWSTR wszPath */
hDevice = CreateFileW(wszPath, // drive to open
0, // no access to the drive
FILE_SHARE_READ | // share mode
FILE_SHARE_WRITE,
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL); // do not copy file attributes
Converting that function call to Delphi is just a matter of changing the syntax:
// wszPath: PWideChar
hDevice := CreateFileW(wszPath,
0,
FILE_SHARE_READ or
FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
0,
0);
That is, use :=
for assignment, or
for combining bit flags, nil
for null pointers, and 0
for null file handles.
The function is called with this:
#define wszDrive L"\\\\.\\PhysicalDrive0"
DISK_GEOMETRY pdg = { 0 }; // disk drive geometry structure
bResult = GetDriveGeometry (wszDrive, &pdg);
Again, just change the syntax to Delphi:
const wszDrive = '\\.\PhysicalDrive0';
var pdg: DISK_GEOMETRY;
ZeroMemory(@pdg, SizeOf(pdg));
bResult := GetDriveGeometry(wszDrive, @pdg);
Delphi untyped string constants are automatically whatever type they need to be in context, so we don't need any L
prefix like C uses. Backslashes aren't special in Delphi, so they don't need to be escaped. Delphi doesn't allow initializing local variables in the declaration, so we use ZeroMemory
to set everything to zero. Use @
instead of &
to get a pointer to a variable.
来源:https://stackoverflow.com/questions/8506767/how-do-i-use-createfile-to-access-a-physical-disk