使用自定义控件在 Windows 窗体中复制/粘贴
我正在使用 Windows 窗体 用 C# 编写一个小型应用程序。我想让我的用户在应用程序周围复制和粘贴数据,并且有一些自定义控件,例如一个颜色选择器。
一些默认控件(至少是文本框)已经具有复制和粘贴功能。我希望我的颜色选择器具有相同的功能,并且还希望顶部有一个“编辑”菜单来复制和粘贴。
目前,我不知道如何以一种很好的方式做到这一点,我当前的策略是抓住 Ctrl + C 和 Ctrl + V 命令和菜单单击并执行使用一些 Win32 的函数 调用查找焦点控件,然后从控件中复制或粘贴数据(根据焦点控件的类型,使用大量 if
语句)。
另一种方法似乎是将按键处理写入每个自定义控件中,但通过这种方法,我不确定如何合并“编辑”菜单功能。
我如何以优雅或更“标准”的方式做到这一点?
I am writing a small application in C# using Windows Forms. I want to let my users copy and paste data around the application and there are some custom controls, for example one is a colour picker.
Some of the default controls (well at least the TextBox) have a copy and paste functionality already. I want to have the same thing with my colour picker, and also want an 'Edit' menu at the top to copy and paste.
At the moment, I can't see how to do this in a nice way, my current tack is to catch the Ctrl + C and Ctrl + V commands and the menu clicks and go through a function which uses some Win32 calls to find the focused control and then copy or paste data from or to the control (with a massive if
statement depending on the type of the focused control).
The alternative seems to be to write key handling into every custom control, but with this method I'm not sure how to incorporate the Edit menu functions.
How do I do this in an elegant or more 'standard' way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是在表单中激活
KeyPreview
,然后按照KeyDown
事件中的逻辑进行操作。但另一种方法可能有用:
如果您的 win 应用程序中有一个菜单(例如 &Edit => Copy (Paste))。
为该菜单启用键盘快捷键
,这样您就可以使用复制粘贴的快捷键。现在只管理您的菜单点击
当然,您可以使您的菜单不可见,如果您愿意不向用户显示它。
=================================================== =============================
更新代码:
多个控件的
The simplest way is to activate
KeyPreview
in the form and then follow the logic inKeyDown
event.But an other approach can be useful:
If you have in your win application a menu (by e.g. &Edit => Copy (Paste)).
Enable for that menus the keyboard shortcuts
So you have your shortcuts to Copy paste. Now manage just your menu clicks
Surely, you can make invisible your menu, if you want do not show it to the user.
===============================================================================
UPDATE
code for multiple controls:
要查找获得焦点的控件:
ContainerControl.ActiveControl
。然后根据控件的类型,您可以设置一个值(使用剪贴板值)。To find the focussed control:
ContainerControl.ActiveControl
. Then depending on the type of control, you can set a value (with the clipboard value).KeyUp 事件解决了我的问题!事件
KeyDown
和KeyPress
没有捕获 Ctrl + C 进行复制!来自 Stack Overflow 问题在文本框中捕获 Ctrl + C:
The KeyUp event solved my problem! Events
KeyDown
andKeyPress
didn't catch Ctrl + C for copy!From Stack Overflow question Catching Ctrl + C in a textbox: