简体   繁体   English

C#中的自定义用户控件…右键单击菜单以复制文本(Java开发人员学习C#)

[英]Custom User Control in C#…Right Click Menu to Copy Text (Java Developer learning C#)

I'm working on a custom user control that essentially displays a name value pair (name is on a black background, value on a white). 我正在使用一个自定义用户控件,该控件实际上显示了一个名称/值对(名称在黑色背景上,值在白色上)。 I have my control displaying correctly, even showing up in Designer and on my build page. 我的控件可以正确显示,甚至可以显示在Designer和构建页面中。

What I'd like to do from here is have the ability to right click on the user control and have a menu come up that has a "Copy Value" option, that when selected will copy the value in the "value" part of the user control to the clipboard. 我想从这里进行的操作是能够右键单击用户控件,并弹出带有“复制值”选项的菜单,该菜单被选中后将在菜单的“值”部分复制值。用户控制剪贴板。 What is the best method of approach? 最好的方法是什么?

I'm not sure where to start since most of the documentation on user controls I've found deals with displaying the control, not necessarily interacting with it. 我不确定从哪里开始,因为我发现有关用户控件的大多数文档都涉及显示控件,而不必与之交互。 Additionally, since I'm still learning C#, I might have left out an important part of my problem in this question, so please point that out if it's the case. 另外,由于我仍在学习C#,因此在该问题中我可能遗漏了问题的重要部分,因此请指出是否是这种情况。

I'm using Visual Studio 2008 (if that matters). 我正在使用Visual Studio 2008(如果有的话)。

Examine the ContextMenu control and the ContextMenu property of other controls. 检查ContextMenu控件其他控件的ContextMenu属性。 By assigning a ContextMenu control to the ContextMeny property of another control, you will have the right-click->popup menu wiring done for you. 通过将ContextMenu控件分配给另一个控件的ContextMeny属性,可以完成右键单击->弹出菜单的连接。 Then you only need to implement the click event of the different menu items in the context menu. 然后,您只需要在上下文菜单中实现不同菜单项的click事件。

Then you can use the Clipboard.SetText (as suggested by BFree) to set the desired value to the clipboard. 然后,您可以使用Clipboard.SetText (由BFree建议)将所需的值设置为剪贴板。

Add a ContextMenu to the control. 将一个ContextMenu添加到控件。 The, hook into the MouseClick (or MouseDown, whichever works better) event and if it's a Right-Click, then call show on the ContextMenu (there are a few overloads, try to mess with them see which works best for you). 将其挂接到MouseClick(或MouseDown,以效果较好的一个为准)事件,如果是右键单击,则在ContextMenu上调用show(有一些重载,请尝试将它们弄乱,看看哪种最适合您)。 Then, in the click event of your context menu, just call Clipboard.SetText(...) to set the value to the clipboard. 然后,在上下文菜单的click事件中,只需调用Clipboard.SetText(...)即可将值设置为剪贴板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM