首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 隱藏「我的電腦」磁碟機圖示:登錄機制 NoDrives 完整實作

     編輯:Delphi

原理說明

Windows 檔案總管讀取登錄值 NoDrives(HKEY_CURRENT_USER 與 HKEY_LOCAL_MACHINE 下的 Software\Microsoft\Windows\CurrentVersion\Policies\Explorer)決定隱藏哪些磁碟機。該值為位元遮罩,第 0 位對應 A:、第 1 位對應 B:、以此類推。

位元遮罩計算

磁碟機 : A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
位元位置: 0  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
十進位值: 1  2  4  8 16 32 64 128 256 ... (2^n)

範例:隱藏 C: (4) 與 E: (16) → NoDrives = 4 + 16 = 20。

完整實作程式碼

uses Registry;

procedure HideDrives(HideMask: Integer);
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    // 當前使用者
    Reg.RootKey := HKEY_CURRENT_USER;
    if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer', True) then
    begin
      Reg.WriteInteger('NoDrives', HideMask);
      Reg.CloseKey;
    end;

    // 本機電腦(需系統管理員權限)
    Reg.RootKey := HKEY_LOCAL_MACHINE;
    if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer', True) then
    begin
      Reg.WriteInteger('NoDrives', HideMask);
      Reg.CloseKey;
    end;
  finally
    Reg.Free;
  end;
end;

procedure ShowDrives;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    // 刪除值即恢復顯示
    Reg.RootKey := HKEY_CURRENT_USER;
    if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer', True) then
    begin
      Reg.DeleteValue('NoDrives');
      Reg.CloseKey;
    end;

    Reg.RootKey := HKEY_LOCAL_MACHINE;
    if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer', True) then
    begin
      Reg.DeleteValue('NoDrives');
      Reg.CloseKey;
    end;
  finally
    Reg.Free;
  end;
end;

使用範例

// 隱藏 C: 與 D:
HideDrives(4 + 8); // 12

// 隱藏所有磁碟機
HideDrives($3FFFFFF); // 26 位全 1

// 恢復顯示
ShowDrives;

重要注意事項

  • 需重新登入或重啟:Explorer 讀取登錄通常在啟動時,修改後需重新啟動 explorer.exe 或重新登入/重啟電腦生效。
  • 僅隱藏圖示:實際磁碟機仍可透過「執行」輸入 C:\、命令提示字元、API 存取,非真正存取控制。
  • 權限:寫入 HKLM 需系統管理員權限(UAC 提升)。
  • 群組原則:企業環境建議使用群組原則 User Configuration\Administrative Templates\Windows Components\File Explorer\Hide these specified drives in My Computer 統一管理。

進階:真正限制存取

若需真正禁止存取,可考慮:

  • NTFS 權限設定(移除使用者/群組的「列出資料夾/讀取資料」權限)。
  • 磁碟機代號移除(diskpart remove letter=C)。
  • 儲存裝置群組原則:Computer Configuration\Administrative Templates\System\Removable Storage Access。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved