这是贡献的一个示例,能够在用户窗体文本框中使用上下文菜单。如下图所示。
在这个示例中,使用类来为文本框添加上下文菜单。
这个类模块处理上下文菜单指令,捕获文本框中的右击操作,并处理剪切、复制和粘贴行为。类模块使用了用户窗体的ActiveControl对象。这段代码甚至可以处理诸如框架和多页等容器控件里的控件。
下面是用户窗体初始化代码,展示了定义和使用类对象是如此的简单。仅需要声明该对象,然后设置每个想要具有上下文菜单功能的文本框的引用。
Private m_colContextMenus As Collection Private Sub UserForm_Initialize() Dim clsContextMenu As CTextBox_ContextMenu Set m_colContextMenus = New Collection Set clsContextMenu = New CTextBox_ContextMenu With clsContextMenu Set .TBox = UserForm1.TextBox1 Set .Parent = Me End With m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1) Set clsContextMenu = New CTextBox_ContextMenu With clsContextMenu Set .TBox = UserForm1.TextBox2 Set .Parent = Me End With m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1) Set clsContextMenu = New CTextBox_ContextMenu With clsContextMenu Set .TBox = UserForm1.TextBox3 Set .Parent = Me End With m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1) Set clsContextMenu = New CTextBox_ContextMenu With clsContextMenu Set .TBox = UserForm1.TextBox4 Set .Parent = Me End With m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1) Set clsContextMenu = New CTextBox_ContextMenu With clsContextMenu Set .TBox = UserForm1.TextBox5 Set .Parent = Me End With m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1) End Sub
示例下载: