提示:
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.