2009-04-08 92 views

回答

3

Python中的以下代碼激活View/Status Bar菜單項。無論如何,將它轉換爲Delphi應該沒有問題,因爲它看起來像僞代碼。它跨越(「View」)和第一個項目(「狀態欄」)選擇第四個菜單項。如果您想要,可以通過遍歷項目並使用GetMenuString來更改它以通過文本搜索所需的項目。有關詳細信息,請參閱MSDN。

請注意,它不會執行任何錯誤檢查。還要注意,它預計記事本的標題是'無標題 - 記事本'。 (你可以改變,要None搜索什麼,我想這將是德爾福nil

from win32gui import * 
from win32con import * 
hwnd = FindWindow('Notepad', 'Untitled - Notepad') # use Winspector Spy to find window class name and title 
hmenu = GetMenu(hwnd) 
hviewmenu = GetSubMenu(hmenu, 3)     # 3rd menu item across, starting from 0 
id = GetMenuItemID(hviewmenu, 0)     # 0th menu item down ("Status Bar") 
PostMessage(hwnd, WM_COMMAND, id, 0) 
2

這裏一些Delphi代碼。
請注意,如果您沒有真正的菜單,則這不起作用。
來自幫助: 「GetMenu無法在浮動菜單欄上工作,浮動菜單欄是模仿標準菜單的自定義控件,它們不是菜單,要使用浮動菜單欄上的句柄,請使用Active Accessibility API。

例如,它不會與德爾福自身工作...

// Grab sub menu for a Window (by handle), given by (0 based) indices in menu hierarchy 
function GetASubmenu(const hW: HWND; const MenuInts: array of Integer): HMENU; 
var 
    hSubMenu: HMENU; 
    I: Integer; 
begin 
    Result := 0; 
    if Length(MenuInts) = 0 then 
    Exit; 

    hSubMenu := GetMenu(hW); 
    if not IsMenu(hSubMenu) then 
    Exit; 

    for I in MenuInts do 
    begin 
    Assert(I < GetMenuItemCount(hSubMenu), format('GetASubmenu: tried %d out of %d items',[I, GetMenuItemCount(hSubMenu)])); 
    hSubMenu := GetSubMenu(hSubMenu, I); 
    if not IsMenu(hSubMenu) then 
     Exit; 
    end; 

    Result := hSubMenu; 
end; 

// Get the caption for MenuItem ID 
function GetMenuItemCaption(const hSubMenu: HMENU; const Id: Integer): string; 
var 
    MenuItemInfo: TMenuItemInfo; 
begin 
    MenuItemInfo.cbSize := 44;   // Required for Windows 95. not sizeof(AMenuInfo) 
    MenuItemInfo.fMask := MIIM_STRING; 
    // to get the menu caption, 1023 first chars should be enough 
    SetLength(Result, 1023 + 1); 
    MenuItemInfo.dwTypeData := PChar(Result); 
    MenuItemInfo.cch := Length(Result)-1; 
    if not GetMenuItemInfo(hSubMenu, Id, False, MenuItemInfo) then 
    RaiseLastOSError; 
    // real caption's size. Should call GetMenuItemInfo again if was too short 
    SetLength(Result, MenuItemInfo.cch); 
    {$WARN SYMBOL_PLATFORM OFF} 
    if DebugHook > 0 then 
    OutputDebugString(MenuItemInfo.dwTypeData); 
end; 

procedure Test; 
var 
    hwnd, hSubMenu: Cardinal; 
    id : Integer; 
begin 
// hwnd := FindWindow('Afx:00400000:8:00010013:00000000:03F61829', nil); // UltraEdit 
// hSubMenu := GetASubmenu(hwnd, [5,0]); 
    hwnd := FindWindow('Notepad', nil); // get the 1st instance of Notepad... 
    hSubMenu := GetASubmenu(hwnd, [3]); // 4th submenu Menu aka &View 

    if hSubMenu > 0 then 
    begin 
    id := GetMenuItemID(hSubMenu, 0); // 1st Item in that sub menu (must not be a submenu itself) 
    if id > -1 then 
    begin 
     PostMessage(hwnd, WM_COMMAND, id, 0); 
     ShowMessage('Done: ' + GetMenuItemCaption(hSubMenu, id)); 
    end 
    else 
     RaiseLastOSError; 
    end 
    else 
    RaiseLastOSError; 
end;