應用程式常需檢測硬體環境(安裝程式檢查規格、多媒體軟體驗證裝置等)。本文示範如何在 BCB 中呼叫 Win32 API 完成六大項硬體偵測,所有範例在 Windows 98 / BCB 4 實測通過。
建立一個表單:一個 TButton (Button1) 與一個 TMemo (Memo1)。所有偵測程式碼放入 Button1Click 事件,結果輸出至 Memo1。
void __fastcall TForm1::Button1Click(TObject *Sender) {
SYSTEM_INFO si;
GetSystemInfo(&si);
Memo1->Lines->Add("CPU 型號: " + IntToStr(si.dwProcessorType));
// 進階:si.dwNumberOfProcessors、si.dwPageSize 等
}
MEMORYSTATUS ms;
ms.dwLength = sizeof(ms);
GlobalMemoryStatus(&ms);
Memo1->Lines->Add("實體記憶體總量: " + IntToStr(ms.dwTotalPhys / 1024 / 1024) + " MB");
Memo1->Lines->Add("可用實體記憶體: " + IntToStr(ms.dwAvailPhys / 1024) + " KB");
// 亦可取得虛擬記憶體:dwTotalVirtual、dwAvailVirtual
DWORD sectorsPerCluster, bytesPerSector, freeClusters, totalClusters;
GetDiskFreeSpace("C:\\", §orsPerCluster, &bytesPerSector, &freeClusters, &totalClusters);
long totalMB = totalClusters * sectorsPerCluster * bytesPerSector / 1024 / 1024;
long freeMB = freeClusters * sectorsPerCluster * bytesPerSector / 1024 / 1024;
Memo1->Lines->Add("C: 總容量: " + IntToStr(totalMB) + " MB");
Memo1->Lines->Add("C: 可用空間: " + IntToStr(freeMB) + " MB");
for (char drive = 'C'; drive <= 'Z'; drive++) {
UINT type = GetDriveType((AnsiString(drive) + ":").c_str());
if (type == DRIVE_CDROM) // 5
Memo1->Lines->Add("發現光碟機: " + AnsiString(drive) + ":");
}
GetDriveType 回傳值:0=未知、1=不存在、2=可移動、3=固定、4=網路、5=光碟機、6=RAM 磁碟。
char volName[255], fsName[100];
DWORD volSerial, maxCompLen, fsFlags;
if (!GetVolumeInformation("G:\\", volName, 255, &volSerial, &maxCompLen, &fsFlags, fsName, 100)) {
Memo1->Lines->Add("G: 無光碟或無法讀取");
} else {
Memo1->Lines->Add("光碟磁碟區標籤: " + AnsiString(volName));
Memo1->Lines->Add("光碟序號: " + IntToStr(volSerial));
}
#include
#pragma comment(lib, "winmm.lib")
int waveDevs = waveOutGetNumDevs();
int midiDevs = midiOutGetNumDevs();
WAVEOUTCAPS woc;
if (waveDevs > 0) {
waveOutGetDevCaps(0, &woc, sizeof(woc));
Memo1->Lines->Add("波形輸出裝置: " + AnsiString(woc.szPname));
} else Memo1->Lines->Add("無波形輸出裝置");
MIDIOUTCAPS moc;
if (midiDevs > 0) {
midiOutGetDevCaps(0, &moc, sizeof(moc));
Memo1->Lines->Add("MIDI 輸出裝置: " + AnsiString(moc.szPname));
} else Memo1->Lines->Add("無 MIDI 裝置");
Memo1->Lines->Add("目前解析度: " + IntToStr(Screen->Width) + " x " + IntToStr(Screen->Height));
HDC hdc = Form1->Canvas->Handle;
int bpp = GetDeviceCaps(hdc, BITSPIXEL); // 每像素位元數
int planes = GetDeviceCaps(hdc, PLANES); // 色彩平面數
long colors = 1;
for (int i = 0; i < bpp * planes; i++) colors *= 2; // 2^(bpp*planes)
Memo1->Lines->Add("目前色深: " + IntToStr(colors) + " 色 (" + IntToStr(bpp*planes) + " bits)");
THardwareInfo 元件,發布 OnDetectionComplete 事件。善用 GetSystemInfo、GlobalMemoryStatus、GetDiskFreeSpace、GetDriveType、waveOutGetNumDevs、GetDeviceCaps 等 API,即可構建完整的硬體偵測模組。更多參數細節請參閱 BCB 線上說明或 MSDN Win32 API 文件。