logo
down
shadow

wxWidgets and context menus


wxWidgets and context menus

By : Juan Carlos
Date : October 20 2020, 11:12 PM
like below fixes the issue wxWidgets is a library to abstract away platform differences, like which mouse or key events should result in a context menu to appear. There may be differences like whether it appears on mouse down, or on mouse up, or even (on the Mac) on Ctrl+click of the single mouse button.
You should therefore not handle mouse and keyboard events directly, but handle the wxContextMenuEvent instead. Note that it will be called after both mouse and keyboard events:
code :


Share : facebook icon twitter icon
How do I show the help strings for wxWidgets popup menus?

How do I show the help strings for wxWidgets popup menus?


By : user2998158
Date : March 29 2020, 07:55 AM
I wish this help you I tried invoking it via the wxFrame instead of the current window (a wxListCtrl). That helped, but not much: it would clear the status bar when the mouse moved over a popup menu item, but wouldn't show the help text for it.
When I dug into the wxWidgets source code, I discovered the reason: my popup menu's items weren't on the menu bar. wxWidgets sends the ID of the menu item to the menu bar to fetch the text, which obviously fails in this case.
code :
////////////////////////////////////////////////////////////////////////////
// In a header file...

class PopupMenu: public wxMenu {
    public: //
    PopupMenu(): mPushed(false) { }

    void OnOpen(wxMenuEvent &evt);
    void OnClose(wxMenuEvent &evt);
    void OnShowMenuHelp(wxMenuEvent &evt);

    private: //
    bool mPushed;

    DECLARE_EVENT_TABLE()
};

////////////////////////////////////////////////////////////////////////////
// In a cpp file...

BEGIN_EVENT_TABLE(PopupMenu, wxMenu)
    EVT_MENU_OPEN(PopupMenu::OnOpen)
    EVT_MENU_CLOSE(PopupMenu::OnClose)
    EVT_MENU_HIGHLIGHT(wxID_ANY, PopupMenu::OnShowMenuHelp)
END_EVENT_TABLE()

void PopupMenu::OnOpen(wxMenuEvent &evt) {
    if (!mPushed) {
        // Clear it
        findStatusBar()->PushStatusText(wxString());
        mPushed = true;
    }
}

void PopupMenu::OnClose(wxMenuEvent &evt) {
    if (mPushed) {
        findStatusBar()->PopStatusText();
        mPushed = false;
    }
}

void PopupMenu::OnShowMenuHelp(wxMenuEvent &evt) {
    if (mPushed) {
        findStatusBar()->SetStatusText(GetHelpString(evt.GetMenuId()));
    } else {
        findStatusBar()->PushStatusText(GetHelpString(evt.GetMenuId()));
        mPushed = true;
    }
}
Why menus and context menus of IntelliJ are instantly closing after beeing opened?

Why menus and context menus of IntelliJ are instantly closing after beeing opened?


By : Dawam
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further It happens when you are using Eclipse keymap, and there is an easy fix for this problem.
See also the related bug in IDEA tracker.
Windows explorer context menus with sub-menus using pywin32

Windows explorer context menus with sub-menus using pywin32


By : userBee
Date : March 29 2020, 07:55 AM
This might help you I found out how to do this after a lot of trial and error and googling.
The example below shows a menu with a submenu and icons.
code :
# A sample context menu handler.
# Adds a menu item with sub menu to all files and folders, different options inside specified folder. 
# When clicked a list of selected items is displayed.
#
# To demostrate:
# * Execute this script to register the context menu. `python context_menu.py --register`
# * Restart explorer.exe- in the task manager end process on explorer.exe. Then file > new task, then type explorer.exe
# * Open Windows Explorer, and browse to a file/directory.
# * Right-Click file/folder - locate and click on an option under 'Menu options'.

import os
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
import win32api

class ShellExtension:
    _reg_progid_ = "Python.ShellExtension.ContextMenu"
    _reg_desc_ = "Python Sample Shell Extension (context menu)"
    _reg_clsid_ = "{CED0336C-C9EE-4a7f-8D7F-C660393C381F}"
    _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
    _public_methods_ = shellcon.IContextMenu_Methods + shellcon.IShellExtInit_Methods

    def Initialize(self, folder, dataobj, hkey):
        print "Init", folder, dataobj, hkey
        win32gui.InitCommonControls()
        self.brand= "Menu options"
        self.folder= "C:\\Users\\Paul\\"
        self.dataobj = dataobj
        self.hicon= self.prep_menu_icon(r"C:\path\to\icon.ico")


    def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
        print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags

        # Query the items clicked on
        files= self.getFilesSelected()

        fname = files[0]
        idCmd = idCmdFirst

        isdir= os.path.isdir(fname)
        in_folder= all([f_path.startswith(self.folder) for f_path in files])

        win32gui.InsertMenu(hMenu, indexMenu,
            win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
            0, None)
        indexMenu += 1

        menu= win32gui.CreatePopupMenu()
        win32gui.InsertMenu(hMenu,indexMenu,win32con.MF_STRING|win32con.MF_BYPOSITION|win32con.MF_POPUP,menu,self.brand)
        win32gui.SetMenuItemBitmaps(hMenu,menu,0,self.hicon,self.hicon)
#        idCmd+=1
        indexMenu+=1

        if in_folder:
            if len(files) == 1:
                if isdir:
                    win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 1"); idCmd+=1
                else:
                    win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 2")
                    win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
                    idCmd+=1
        else:
            win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 3")
            win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
            idCmd+=1

        if idCmd > idCmdFirst:
            win32gui.InsertMenu(menu,1,win32con.MF_SEPARATOR,0,None)

        win32gui.InsertMenu(menu,2,win32con.MF_STRING,idCmd,"Item 4")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1
        win32gui.InsertMenu(menu,3,win32con.MF_STRING,idCmd,"Item 5")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1

        win32gui.InsertMenu(menu,4,win32con.MF_SEPARATOR,0,None)

        win32gui.InsertMenu(menu,5,win32con.MF_STRING|win32con.MF_DISABLED,idCmd,"Item 6")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1

        win32gui.InsertMenu(hMenu, indexMenu,
                            win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
                            0, None)
        indexMenu += 1
        return idCmd-idCmdFirst # Must return number of menu items we added.

    def getFilesSelected(self):
        format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
        sm = self.dataobj.GetData(format_etc)
        num_files = shell.DragQueryFile(sm.data_handle, -1)
        files= []
        for i in xrange(num_files):
            fpath= shell.DragQueryFile(sm.data_handle,i)
            files.append(fpath)
        return files

    def prep_menu_icon(self, icon): #Couldn't get this to work with pngs, only ico
        # First load the icon.
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
        hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE)

        hdcBitmap = win32gui.CreateCompatibleDC(0)
        hdcScreen = win32gui.GetDC(0)
        hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
        hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
        # Fill the background.
        brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
        win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
        # unclear if brush needs to be feed.  Best clue I can find is:
        # "GetSysColorBrush returns a cached brush instead of allocating a new
        # one." - implies no DeleteObject
        # draw the icon
        win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
        win32gui.SelectObject(hdcBitmap, hbmOld)
        win32gui.DeleteDC(hdcBitmap)

        return hbm

    def InvokeCommand(self, ci):
        mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
        win32gui.MessageBox(hwnd, str(self.getFilesSelected()), "Wow", win32con.MB_OK)

    def GetCommandString(self, cmd, typ):
        # If GetCommandString returns the same string for all items then
        # the shell seems to ignore all but one.  This is even true in
        # Win7 etc where there is no status bar (and hence this string seems
        # ignored)
        return "Hello from Python (cmd=%d)!!" % (cmd,)

def DllRegisterServer():
    import _winreg
    folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
    "Folder\\shellex")
    folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers")
    folder_subkey2 = _winreg.CreateKey(folder_subkey, "PythonSample")
    _winreg.SetValueEx(folder_subkey2, None, 0, _winreg.REG_SZ,
    ShellExtension._reg_clsid_)

    file_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
    "*\\shellex")
    file_subkey = _winreg.CreateKey(file_key, "ContextMenuHandlers")
    file_subkey2 = _winreg.CreateKey(file_subkey, "PythonSample")
    _winreg.SetValueEx(file_subkey2, None, 0, _winreg.REG_SZ,
    ShellExtension._reg_clsid_)

    print ShellExtension._reg_desc_, "registration complete."

def DllUnregisterServer():
    import _winreg
    try:
        folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,

        "Folder\\shellex\\ContextMenuHandlers\\PythonSample")
        file_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,

        "*\\shellex\\ContextMenuHandlers\\PythonSample")
    except WindowsError, details:
        import errno
        if details.errno != errno.ENOENT:
            raise
    print ShellExtension._reg_desc_, "unregistration complete."

if __name__=='__main__':
    from win32com.server import register
    register.UseCommandLine(ShellExtension,
                   finalize_register = DllRegisterServer,
                   finalize_unregister = DllUnregisterServer)
Empty wxWidgets menus on OSX

Empty wxWidgets menus on OSX


By : Anwar MOHAMMED
Date : March 29 2020, 07:55 AM
should help you out It seems there's no standard way for hiding menus in wxWidgets.
I ended up writing a few lines of Objective-C code to find and hide empty menus:
code :
// MacMenuWorkaround.h

#import <Cocoa/Cocoa.h>

@interface MacMenuWorkaround : NSObject

+(void) hideEmptyMenus;

@end
// MacMenuWorkaround.m

#import "MacMenuWorkaround.h"

@implementation MacMenuWorkaround

+(void) hideEmptyMenus {
    NSMenu* mainMenu = [[NSApplication sharedApplication] mainMenu];

    for (NSMenuItem* item in [mainMenu itemArray]) {
        NSMenu* menu = [item submenu];

        if ([[menu itemArray] count] < 2) {
            [item setHidden:YES];
        }
    }
}

@end
// MacMenuWorkaroundBridge.h

#ifndef __wxstarter__MacMenuWorkaroundBridge__
#define __wxstarter__MacMenuWorkaroundBridge__

namespace CocoaBridge {
    void hideEmptyMenus();
}

#endif /* defined(__wxstarter__MacMenuWorkaroundBridge__) */
// MacMenuWorkaroundBridge.cpp
// Set file type to Objective-C++ Source

#import "MacMenuWorkaround.h"
#include "MacMenuWorkaroundBridge.h"

namespace CocoaBridge {
    void hideEmptyMenus() {
        [MacMenuWorkaround hideEmptyMenus];
    }
}
#include "MacMenuWorkaroundBridge.h"
//...
#if defined(__WXMAC__) || defined(__WXOSX__) || defined(__WXOSX_COCOA__)
CocoaBridge::hideEmptyMenus();
#endif
Does Apples UI define Drag&Drop in menus and/or context menus for menu items

Does Apples UI define Drag&Drop in menus and/or context menus for menu items


By : user3816051
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Well, you can put a view into a menu item, and you can drag from a view, but I don't know whether those two will work together (i.e., whether you can drag from a view that's in a menu item).
More importantly, this isn't normal on the Mac, so you need another place to drag the item from regardless of whether you can support dragging from the menu or not.
Related Posts Related Posts :
  • `LoadLibraryExW` triggers exception `0xC0000023` from `NtMapViewOfSection`
  • static_cast to a struct type to access all of its member variable
  • Forward declaration for boost::intrusive_ptr class to reduce compile time
  • How to use priority_queue with a non-static compare method of class instance?
  • Template parameters inside and outside class/struct
  • Determining prime number
  • How to resolve ambiguity between constructors taking std::string and std::vector
  • My program crashes when I try to change private values from an object
  • Unordered_map with custom class as key
  • Strict aliasing rules broken with templates and inheritance
  • C++ Derived Class Override Return Type
  • singly linked list c++ constructor, destructor and printing out
  • How to clone class with vector of unique_ptr to base class
  • error: no match for operator
  • std::vector doesnt accept my struct as template
  • selection of people's contours
  • how to fix the (Error using mexOpenCV) on matlab?
  • Is or was there a proposal for c++ to use the context for short enum values?
  • Fair assumptions about std::hash implementations
  • undefined reference to libusb using cyusb
  • Function returns null pointer instead of address
  • C++17 copy elision and object destruction
  • Input multiple strings via operator>> c++
  • Avoiding overflow boost container
  • How to Write a Lambda Wrapping a Function with Optional Return Value
  • Partial specialization with more template parameters
  • How to convert fixed size array to pointer on pointer array
  • Memory leak in const member constructor with tag dispatching
  • C++ function with a generic and optional class
  • Custom QGraphicsItem That Contains Child QGraphicsItems
  • Are There Restrictions on What can be Passed to auto Template Parameters?
  • Rotating line inside rectangle bounds
  • Why do I need dynamic memory allocation if I can just create an array?
  • How can I convert a text file into a form that MPI_Bcast can send?
  • How to get array of all `this` of an instance
  • Using pointers as parameters
  • Automatic type deduction with const_cast is not working
  • Why does std::is_rvalue_reference not do what it is advertised to do?
  • Function Template Specialization with Forward Declared Type
  • template deduction failed in vector
  • Is there a signed `sizeof` alternative in Qt
  • clarification on overloading the -> operator
  • What is __m128d?
  • QtConcurrent: why releaseThread and reserveThread cause deadlock?
  • Function receiving different value than passed
  • Can C++ close a '''fstream''' variable after '''.close()'''?
  • Is it necessary to overload operator in this specific case
  • Comparing an element of a string array with a string
  • how to dereference a pointer of a map of pointers to objects in c++
  • How recursive function control flow change for static variable?
  • SDL 2 blitting BMP File
  • Why does an extremely large value cause this code to repeat infinitely?
  • Function returning different value than what is in function body before return statement
  • Struggling with including Headers in another header file (C++)
  • WebViewProcessControl initialization crash
  • C++ exception 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00C02F30)
  • What's difference between forward and move in the constructor of class?
  • C++: Is it possible to condense `bool` objects within the same byte?
  • I cant understand this access modifier
  • Boost Spirit X3: Collapsing one-element lists
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org