开发者

WinForm: Merge ContextMenuStrip MenuItem with existing menu in VS2010

开发者 https://www.devze.com 2023-03-11 11:25 出处:网络
I have added a few custom MenuItem obje开发者_开发问答cts to a ContextMenuStrip control. However, adding my objects has completely blown away the very useful menu items that already existed in the co

I have added a few custom MenuItem obje开发者_开发问答cts to a ContextMenuStrip control.

However, adding my objects has completely blown away the very useful menu items that already existed in the controls (TreeView, TextBox, and DataGridView).

Has anyone been able to successfully merge these items?


No, you can't merge them. You'll have to duplicate the functionality yourself by adding the appropriate menu items and writing the necessary code in their Click event handler methods.

The common controls provide that menu by default. If you wish to override it, you can do so, but there is no built-in provision for combining your custom items with the built-in menu. Some have taken advantage of this as a feature, assigning an empty ContextMenu or ContextMenuStrip to the control in order to prevent the standard menu from ever being displayed (talk about confusing UI design!).

For the TextBox control in particular, I highly recommend that you leave the default context menu as-is rather than trying to re-create it. There are lots of options that it exposes for things like IME that are extremely difficult to get right yourself. If you're targeting your application to the general public, they'll very much appreciate that such functionality exists in your app as expected.

It's best to place your custom functionality somewhere else entirely. Right-clicking a common control and expecting to see a list of custom options is pretty unintuitive. Most other applications don't work that way for precisely this reason.


If, despite my recommendations to the contrary, you were quite insistent upon getting this to work, you might take advantage of the knowledge that the built-in context menu is just a standard Win32 pop-up menu that is displayed by all of the common controls, and that controls send their parent a WM_INITMENUPOPUP message when a pop-up menu is about to become active.

Armed with that knowledge, you might decide to P/Invoke some functions from the Windows API and modify that context menu. In particular, the AppendMenu or SetMenuIteminfo functions.

But then, a surprise will await you. It turns out that the native Edit control (which the TextBox is a representative of) does not send a WM_INITMENUPOPUP message! I'm not sure about the TreeView control, and the DataGridView control won't do any of this because it's a custom class written for WinForms. It's not based on any of the native Win32 controls at all, so it won't be sending any such messages that you can handle.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号