假如我們用 TMainMenu 控制項設計如下菜單:
該菜單在表單源檔案中是這樣儲存的:
object MainMenu1: TMainMenuLeft = 160Top = 104object 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' endendobject Edit1: TMenuItem Caption = '&Edit' object Cut1: TMenuItem Caption = 'Cu&t' end object Copy1: TMenuItem Caption = '&Copy' end object Paste1: TMenuItem Caption = '&Paste' endendobject Help1: TMenuItem Caption = '&Help' object About1: TMenuItem Caption = '&About' endend
在 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 MenuBegin 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" EndEnd
調用代碼:
和原來的程式只有兩行不同:
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.
: