该菜单在窗体源文件中是这样存储的:
object MainMenu1: TMainMenu
Left = 160
Top = 104
object File1: TMenuItem
Caption = '&File'
object New1: TMenuItem
Caption = '&New'
end
object Open1: TMenuItem
Caption = '&Open'
end
object Save1: TMenuItem
Caption = '&Save'
end
object SaveAs1: TMenuItem
Caption = 'Save &As'
end
object N1: TMenuItem
Caption = '-'
end
object Exit1: TMenuItem
Caption = 'E&xit'
end
end
object Edit1: TMenuItem
Caption = '&Edit'
object Cut1: TMenuItem
Caption = 'Cu&t'
end
object Copy1: TMenuItem
Caption = '&Copy'
end
object Paste1: TMenuItem
Caption = '&Paste'
end
end
object Help1: TMenuItem
Caption = '&Help'
object About1: TMenuItem
Caption = '&About'
end
end
在 VC 中, 菜单设计是要保存在资源源文件(*.rc)中, 不管是 VC 还是 Delphi 用什么临时储存方式, 但最终都会被编译成相同的资源文件(*.res).
在 Delphi 中如果想要更灵活地使用菜单, 也回避不了使用资源文件.
原来在学习资源文件时曾经简单接触过菜单资源( 参考以前的内容), 不过这次要站在 Windows 的角度, 涉及更多内容!
下面是和上例对应的资源文件.
建立步骤:
1、新建控制台工程, 保存! 然后再建立资源文件;
2、建立资源文件: File -> New -> Other... -> Text , 写入下面资源文件代码, 和工程保存在相同文件夹, 保存为 *.rc, 我这里使用的是: TestRes.rc;
3、然后从工程中导入资源文件(Project Manager 窗口, 右键点击工程名 - Add);
此时工程代码会自动增加一行: {$R 'TestRes.res' 'TestRes.rc'}
4、注意: 在次以后在工程中修改资源名, 工程代码会随之改变; 修改资源代码后需要先保存, 编译时才有效!
5、另外, 菜单资源的写法还是挺复杂的、功能也很强大; 后面的例子再说.
MyMenu1 Menu
Begin
Popup "&File"
Begin
MenuItem "&New"
MenuItem "&Open"
MenuItem "&Save"
MenuItem Separator
MenuItem "E&xit"
End
Popup "&Edit"
Begin
MenuItem "Cu&t"
MenuItem "&Copy"
MenuItem "&Paste"
End
Popup "&Help"
Begin
MenuItem "&About"
End
End
调用代码:
和原来的程序只有两行不同:
1、{$R 'TestRes.res' 'TestRes.rc'} --- 这是插入资源文件
2、cls.lpszMenuName := 'MyMenu1'; --- 这是指定菜单
program Project1;
{$R 'TestRes.res' 'TestRes.rc'}
uses
Windows,
Messages,
SysUtils;
function WndProc(wnd: HWND; msg: UINT; wParam: Integer; lParam: Integer): Integer; stdcall;
begin
Result := 0;
case msg of
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'; {在这里指定菜单资源, 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.
效果图: