The simplest way is to activate KeyPreview
in the form and then follow the logic in KeyDown
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
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new
System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem});
this.editToolStripMenuItem.Text = "Edit";
//
// copyToolStripMenuItem
//
**this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));**
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
**this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));**
this.pasteToolStripMenuItem.Text = "&Paste";
So you have your shortcuts to Copy paste. Now manage just your menu clicks
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Image myData = this.ActiveControl.BackgroundImage;
Clipboard.SetImage(myData);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
Image myData = Clipboard.GetImage();
this.ActiveControl.BackgroundImage = myData;
}
Surely, you can make invisible your menu, if you want do not show it to the user.
===============================================================================
UPDATE
code for multiple controls:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
ICopyPasteable control = sender as ICopyPasteable;
if (control != null)
{
control.CopyToClipboard();
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
ICopyPasteable control = sender as ICopyPasteable;
if (control != null)
{
control.PasteFromClipboard();
}
}
}
public interface ICopyPasteable
{
void CopyToClipboard();
void PasteFromClipboard();
}
public class MyTextBox : TextBox, ICopyPasteable
{
#region ICopyPasteable Membres
public void CopyToClipboard()
{
Clipboard.SetText(this.Text);
}
public void PasteFromClipboard()
{
if (Clipboard.ContainsText())
{
this.Text = Clipboard.GetText();
}
}
#endregion
}