/
lock.c
55 lines (49 loc) · 1.7 KB
/
lock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <winioctl.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Not enough arguments!\n");
printf("Usage: %s <drive> [unlock]\n", argv[0]);
printf("Example: %s d\n", argv[0]);
printf("Example: %s d unlock\n", argv[0]);
printf("Note:\n");
printf("* You must have a CD in the CD-ROM drive for this to work.\n");
printf("* You can also drag a CD-ROM drive to this exe to lock it.\n");
printf("* If you lock a drive multiple times, you must unlock it just as many times.\n");
return 0;
}
// Unlock?
BOOL lock = TRUE;
if (argc > 2) {
lock = FALSE;
}
// Get handle to drive
char drive[] = "\\\\.\\X:"; // \\.\X:
drive[4] = argv[1][0];
HANDLE device = CreateFile(drive, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (device == INVALID_HANDLE_VALUE) {
printf("CreateFile() failed. GetLastError(): %d.\n", GetLastError());
printf("Query string: %s\n", drive);
return 1;
}
// Lock/Unlock the drive
printf("%s cd-rom drive ... ", (lock?"Locking":"Unlocking")); fflush(stdout);
DWORD bytesReturned; //Not used
PREVENT_MEDIA_REMOVAL pmr = { lock }; //This is really just a BOOL
BOOL result = DeviceIoControl(device, IOCTL_STORAGE_MEDIA_REMOVAL, &pmr, sizeof(pmr), NULL, 0, &bytesReturned, NULL);
if (result == 0) {
printf("DeviceIoControl() failed. GetLastError(): %d.\n", GetLastError());
}
else {
printf("Success!\n");
}
// Clean up
CloseHandle(device);
return 0;
}
// Further reading:
// http://techsupt.winbatch.com/TS/T000001010F28.html
// https://arkeon.dyndns.org/svn-scol/trunk/plugins/lib2d%20os%2024/tmp/source/script2.cpp
// IOCTL_STORAGE_MEDIA_REMOVAL on MSDN