提示:
1、CheckMenuItem 函數用來改變菜單項的選擇狀態;
2、SetClassLong 函數可以修改窗口類注冊前登記的所有參數, 這裡通過 GCL_HBRBACKGROUND 參數指示要修改畫刷;
3、用 CreateSolidBrush 函數根據常量數組中的顏色建立實心畫刷;
4、InvalidateRect 用來是客戶區無效, 從而導致重繪, 它的第二個參數為 nil 表示要操作的矩形是當前窗口客戶區;
5、在資源文件中, 給菜單項指定了 MFT_RADIOCHECK, 是讓被選菜單顯示一個小圓點.
另外: 這和 前面的一個例子 有些類似, 但區別很大; 前者改變用戶區顏色是矩形填充, 這裡是直接修改窗口類的畫刷.
本例效果圖:
本例使用的資源文件(TestRes.rc):
MyMenu1 MENUEX
BEGIN
POPUP "&Color"
BEGIN
MENUITEM "White" ,101 ,MFT_RADIOCHECK ,MFS_CHECKED
MENUITEM "Red" ,102 ,MFT_RADIOCHECK
MENUITEM "Green" ,103 ,MFT_RADIOCHECK
MENUITEM "Blue" ,104 ,MFT_RADIOCHECK
END
END
本例代碼文件:
program Project1;
{$R 'TestRes.res' 'TestRes.rc'}
uses
Windows, Messages;
const
arrColor: array[0..3] of COLORREF = ($FFFFFF, $FF, $FF00, $FF0000);
IDM_White = 101; {101 表示第一個菜單項, 是在資源文件中指定的}
var
IDM_ID: Word = IDM_White;
{收到 WM_COMMAND 消息時需要做的工作}
procedure OnCommand(h: HWND; wParam: Integer);
var
HM: HMENU;
W: Word;
begin
HM := GetMenu(h);
W := LoWord(wParam);
case W of
101..104: begin
CheckMenuItem(HM, IDM_ID, MFS_UNCHECKED);
IDM_ID := W;
CheckMenuItem(HM, IDM_ID, MFS_CHECKED);
SetClassLong(h, GCL_HBRBACKGROUND, CreateSolidBrush(arrColor[W - IDM_White ]));
InvalidateRect(h, nil, True);
end;
end;
end;
function WndProc(wnd: HWND; msg: UINT; wParam,lParam: Integer): Integer; stdcall;
begin
Result := 0;
case msg of
WM_COMMAND : OnCommand(wnd, wParam); {收到 WM_COMMAND 消息後調用 OnCommand 過程}
WM_DESTROY : PostQuitMessage(0);
else
Result := DefWindowProc(wnd, msg, wParam, lParam);
end;
end;
function RegMyWndClass: Boolean;
var
cls: TWndClass;
begin
cls.style := CS_HREDRAW or CS_VREDRAW;
cls.lpfnWndProc := @WndProc;
cls.cbClsExtra := 0;
cls.cbWndExtra := 0;
cls.hInstance := HInstance;
cls.hIcon := 0;
cls.hCursor := LoadCursor(0, IDC_ARROW);
cls.hbrBackground := HBRUSH(COLOR_WINDOW + 1);
cls.lpszMenuName := 'MyMenu1';
cls.lpszClassName := 'MyWnd';
Result := RegisterClass(cls) <> 0;
end;
{程序入口}
const
tit = 'New Form';
ws = WS_OVERLAPPEDWINDOW;
x = 100; y = 100; w = 300; h = 180;
var
hWnd: THandle;
Msg : TMsg;
begin
RegMyWndClass;
hWnd := CreateWindow('MyWnd', tit, ws, x, y, w, h, 0, 0, HInstance, nil);
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
while(GetMessage(Msg, 0, 0, 0)) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end.