在 C++Builder 中直接於 Windows 桌面繪製圖像,可用於建立桌面小工具、螢幕標註、教學演示等應用。本文提供最小化完整範例,關鍵在於取得桌面視窗 DC 並繪製至其上。
class TForm1 : public TForm {
private:
Graphics::TBitmap* Bmp; // 圖像資源
// ...
};
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
Bmp = new Graphics::TBitmap();
Bmp->LoadFromFile(L"C:\\AboutLogo.bmp"); // 使用寬字串路徑
}
void __fastcall TForm1::FormPaint(TObject* Sender) {
HDC hDeskDC = GetWindowDC(GetDesktopWindow()); // 取得桌面 DC
RECT rect;
GetWindowRect(GetDesktopWindow(), &rect); // 取得桌面矩形
// 計算置中座標
int x = (rect.right - rect.left - Bmp->Width) / 2;
int y = (rect.bottom - rect.top - Bmp->Height) / 2;
// 繪製位圖至桌面 DC
BitBlt(hDeskDC, x, y, Bmp->Width, Bmp->Height,
Bmp->Canvas->Handle, 0, 0, SRCCOPY);
ReleaseDC(GetDesktopWindow(), hDeskDC); // 釋放 DC
}
__fastcall TForm1::~TForm1() {
delete Bmp;
}
| API | 用途 |
|---|---|
GetDesktopWindow() | 取得桌面視窗控制代碼 (覆蓋全螢幕的視窗) |
GetWindowDC(hwnd) | 取得視窗完整繪圖環境 (含非客戶區) |
GetWindowRect(hwnd, &rect) | 取得視窗螢幕座標矩形 |
BitBlt(hdcDst, x, y, w, h, hdcSrc, xSrc, ySrc, SRCCOPY) | 像素區塊傳輸繪製 |
ReleaseDC(hwnd, hdc) | 釋放 GetWindowDC 取得的 DC |
ReleaseDC 配對呼叫,避免 GDI 物件洩漏WS_EX_LAYERED)Windows.UI.Composition 或桌面小工具架構此技巧雖簡單,但理解 DC、視窗座標、GDI 繪圖流程對 Windows 圖形程式設計基礎極有幫助。