Tutto quello che avreste voluto sapere sull’Owner-Drawing
http://msdn.microsoft.com/msdnmag/issues/04/02/CuttingEdge/default.aspx
In questo articolo Dino Esposito tratta in maniera approfondita i seguenti argomenti:
– Customizing Menu Rendering
– Overriding the Menu of a Form
– The MeasureItem Event
– The DrawItem Event
– Painting the Menu Item
– Context Menu and TextBoxes
– Using Graphical Menus Seamlessly
e risponde implicitamente ad un mio dubbio circa la possibilità di personalizzare il context menu di default del TextBox:
The Textbox is the only control in Windows Forms that has a built-in context menu. The control exposes a ContextMenu property, but it doesn’t return an instance of the context menu that appears when you right-click. Why? The code for the textbox’s context menu is hardcoded in the Win32 API. In particular, the context menu is generated on the fly each time the user right-clicks. The menu is then released and destroyed once the selection is made. You can replace this menu with your own by setting the ContextMenu property, but there’s no chance to manipulate the original menu. Since the menu has a very short (and unmanaged) life, how can you easily subclass it and mark it as owner-draw?
The simplest trick that I’ve found is the following: create a TextboxContextMenu class that represents a custom context menu with all of the items of a standard textbox context menu (Undo, Cut, Copy, and the like). Implementing these methods is relatively simple and samples can be found in the MSDN documentation. Once you hold an instance of a managed class that works like the typical context menu of a TextBox, you first make it owner-draw and then you bind it to any TextBox you want:
Dim txtMenu As New TextBoxContextMenu gMenu.AddIcon(txtMenu.MenuItemCut, "..\images\cut.bmp") gMenu.AddIcon(txtMenu.MenuItemCopy, "..\images\copy.bmp") gMenu.AddIcon(txtMenu.MenuItemPaste, "..\images\paste.bmp") gMenu.AddIcon(txtMenu.MenuItemDelete, "..\images\delete.bmp") TextBox1.ContextMenu = txtMenu gMenu.Init(TextBox1.ContextMenu)
The TextBoxContextMenu class lives in the same assembly that contains the GraphicMenu class. You should be aware that owner-drawn menus don’t work correctly when attached to a NotifyIcon component. For more information on this problem see Knowledge Base article 827043.